开发者

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;
    }
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜