Wednesday, 23 April 2014

Using LinqKit and PredicateBuilder to create reusable predicates or filters in Entity Framework

If one has worked with Entity Framework for a while, sooner or later it becomes clear that refactoring logic into separate methods is hard, because Entity Framework must transform the code one writes in Linq to Entities into SQL. Therefore, extracting logic in EF into method calls will compile, but give a runtime error. The solution is to use the library LinqKit, created by brothers Joe and Ben Albahiri. It is available as a Nuget package: install-package LinqKit or at the following web site: LinqKit

The following simple example shows how it is possible to create a reusable predicate separated into a method of its own and call this method in Linq to entities code. Make note of the use of the AsExpandable() extension method that transforms the DbSet into an IQueryable by returning a wrapper that allows this. The code is run inside LinqPad. Make note that LinqPad has got inherent support for PredicateBuilder, but the LinqKit DLL was added as a reference. Also the namespace imports added where: System.Linq, System.Linq.Expressions and LinqKit. Press F4 to set up the additional references and imports in Linqpad.

public Expression<Func<Patient, bool>> InterestingPatient(params string[] keywords){
 var predicate = PredicateBuilder.False<Patient>(); 
 foreach (string keyword in keywords){
  string temp = keyword; 
  predicate = predicate.Or(p => p.Name.Contains(temp)); 
 }
 return predicate; 
}

void Main()
{
   Patients.AsExpandable().Where(InterestingPatient("Olsen", "Nilsen")).Dump(); 
}




The following images shows the output. Make note that Patient here is a table in the context of my project. The data shown here is test data (not real pasients of course):

Wednesday, 5 March 2014

Entity Framework Code First Generic Entity store operations

This article will discuss how generic entity store operations towards a data context can be used with EF Code First. This is tested with EF 6. First, define an interface with the often used generic entity store operations:

using System;
using System.Data.Entity;

namespace TestEFCodeFirst1
{

    public interface IRepo : IDisposable
    {

        T Insert<T>(T item, bool saveNow) where T : class;

        T Update<T>(T item, bool saveNow) where T : class;

        T Delete<T>(T item, bool saveNow) where T : class;

        int Save(); 

    }

}

Then implement this interface:

using System.Data.Entity;

namespace TestEFCodeFirst1
{
    
    public class Repo<TContext> : IRepo
        where TContext : DbContext, new()
    {

        public Repo()
        {
            Context = new TContext(); 
        }

        protected TContext Context { get; private set; }

        #region IRepo Members

        public T Insert<T>(T item, bool saveNow) where T : class
        {
            Context.Entry(item).State = EntityState.Added;
            if (saveNow)
                Context.SaveChanges();
            return item; 
        }

        public T Update<T>(T item, bool saveNow) where T : class
        {
            Context.Entry(item).State = EntityState.Modified;
            if (saveNow)
                Context.SaveChanges();
            return item; 
        }

        public T Delete<T>(T item, bool saveNow) where T : class
        {
            Context.Entry(item).State = EntityState.Deleted;
            if (saveNow)
                Context.SaveChanges();
            return item; 
        }

        public void Dispose()
        {
            Context.Dispose(); 
        }

        #endregion

        #region IRepo Members


        public int Save()
        {
            return Context.SaveChanges(); 
        }

        #endregion
    }

}

Next, create a simple DbContext to test out:

  
  public class DemoDbContext : DbContext
    {


        public DemoDbContext() : base("EFCodeFirstDemoDb1")
        {
            
            
        }


        public DbSet<Student> Students { get; private set; }

    }


An example of using this db context in a derived repo class is shown next:

public class DemoRepo : Repo<DemoDbContext>
{

}

The next code shows how to use this extension method:

using System;
using System.Data.Entity;

namespace TestEFCodeFirst1
{
    class Program
    {
        static void Main(string[] args)
        {

            Database.SetInitializer(new Init()); 

            using (var repo = new DemoRepo())
            {
                repo.Insert(new Student { Name = "Hardy", DateAdded = DateTime.Now,
                LastMod = DateTime.Now}, true);

                repo.Insert(new Student
                {
                    Name = "Joey",
                    DateAdded = DateTime.Now,
                    LastMod = DateTime.Now
                }, true);                

            }
        }

    }
}


To automatically patch your database do this:

In package-manager console type: Enable-Migrations In the configuration class, set AutomaticMigrationsEnabled to true.

namespace TestEFCodeFirst1.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<TestEFCodeFirst1.DemoDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(TestEFCodeFirst1.DemoDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}


Add an Init class:

using TestEFCodeFirst1.Migrations;

namespace TestEFCodeFirst1
{

    internal class Init : System.Data.Entity.MigrateDatabaseToLatestVersion
    {

    }
}

This explains what is done in the line further up: Database.SetInitializer(new Init());

Tuesday, 18 February 2014

Performing slow work outside the WPF UI thread and updating the WPF GUI afterwards

Developers using WPF are very familiar with the problem of doing slow work on the UI thread and trying to update the GUI thread afterwards. This is not only a problem in WPF, but also in Windows Forms and even web applications. If the UI thread is being kept busy with a heavy, synchronous calculation, other work such as resizing the window and even repainting the UI will suffer and this results in a non-responsive GUI that the user cannot work with. The solution is to do work in another thread or threads and update the GUI afterwards. To make this easier, I list up an extension method below to do this. The extension method is an extension method on the dispatcher, which will usually be this.Dispatcher in code behind or Dispatcher.CurrentDispatcher in MVVM scenarios and the user must supply the function that will return the thread work return a type T (this can be either an object or a list of objects for example) and also a gui update method that receives an object of type T that the thread work method calculated. The gui update method will usually specify what shall be performed in the GUI or in the ViewModel in MVVM scenarios, while the thread work method specifies first will specify how the object of type T is retrieved. It should be possible to use this extension method both in code-behind and MVVM scenarios.

public static class DispatcherUtil
    {

        public static void AsyncWorkAndUIThreadUpdate<T>(this Dispatcher currentDispatcher, Func<T> threadWork, Action<T> guiUpdate)
        {
            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                T resultAfterThreadWork = threadWork(); 
                currentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action<T>(delegate(T result){
                    guiUpdate(resultAfterThreadWork);
                }), resultAfterThreadWork); 

            }); 
        }

    }

Next, an example of using this:

  private void Button_Click(object sender, RoutedEventArgs e)
        {

            this.Dispatcher.AsyncWorkAndUIThreadUpdate(() => FooService.GetSomeFooData(),
                s => btnFoo.Content = s); 

        }

The FooService is very simple and simulates a resource intensive calculation that takes about 5 seconds:

public static class FooService
    {

        public static string GetSomeFooData()
        {
            Thread.Sleep(5000);
            return "Hello world! "  + DateTime.Now.ToString(); 
        }

    }

I use ThreadPool.QueueUserWorkItem here. Of course this is a very simple example, and in complex applications one needs to watch out for state problems in the UI. When it is not sure when the calculation is performed, you should perhaps consider to avoid refreshing the UI if the UI has changed, especially in more complex MVVM component based WPF User Interfaces, based on for example Prism. At the same time, locking up the UI is not good either. I have only tested the code above in a simple scenario, but expect it to work also with more complex WPF UI. There are two golden rules when it comes to threading in WPF: 1. Never access UI elements from another thread than the UI thread 2. Do not do slow work on the UI thread but in another thread Most difficulties doing off thread async work in WPF comes to updating the UI after the calcuations are done in the other thread(s). With this extension method, hopefully WPF developers will find it easier.