17

I am using the Code-First approach with EF and I wanted to use IDbSet instead of DbSet so I could do Unit Testing with mocks. My problem is I use the Include() method for eager loading where necessary but Include() is not exposed via IDbSet. I saw an example code using an extension method to expose Include() but it doesn't seem to work for me; the objectQuery object in this example is always null. Please let me know how to fix this.

public static class IQueryableExtension
{
    public static IQueryable<T> Include<T>(this IQueryable<T> source, string path)
        where T : class
    {
        ObjectQuery<T> objectQuery = source as ObjectQuery<T>;
        if (objectQuery != null)
        {
            return objectQuery.Include(path);
        }
        return source;
    }

    public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, 
        System.Linq.Expressions.Expression<Func<T, TProperty>> path)
        where T : class
    {
        ObjectQuery<T> objectQuery = source as ObjectQuery<T>;
        if (objectQuery != null)
        {
            return source.Include(path);
        }
        return source;
    }
}
enamrik
  • 2,292
  • 2
  • 27
  • 42

2 Answers2

28

You don't need to write such extension if you are using CTP5. CTP5 provides Include extension for IQueryable. You have to reference EntityFramework.dll (CTP5) and add:

using System.Data.Entity;

Your version probably doesn't work because your are converting source to ObjectQuery but it will most probably be of type DbQuery.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I didn't get what you were saying at first. But then I realized I needed to have the using statement on the file where I was writing my linq statement (services class) to use Include(), not just on the file I created my DbContext (session.cs). Thank you!!! – enamrik Feb 09 '11 at 21:34
  • 1
    alas, the quest for unit testable EF has reached it's goal. THANKS. – Elad Katz Aug 16 '11 at 16:02
0

Make sure you have the property using statements that contain the above static class. Simple copy/paste of your code results in IDbSet exposing the include methods when referencing the proper namespace.

Buildstarted
  • 26,529
  • 10
  • 84
  • 95