Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDbSet and Exposing Include method via Extension Method

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;
    }
}
like image 296
enamrik Avatar asked Feb 09 '11 21:02

enamrik


1 Answers

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.

like image 68
Ladislav Mrnka Avatar answered Oct 21 '22 07:10

Ladislav Mrnka