【问题标题】:IDbSet and Exposing Include method via Extension MethodIDbSet 和通过扩展方法公开包含方法
【发布时间】:2011-02-10 05:18:24
【问题描述】:

我在 EF 中使用 Code-First 方法,并且我想使用 IDbSet 而不是 DbSet,因此我可以使用 mock 进行单元测试。我的问题是我在必要时使用 Include() 方法进行预加载,但 Include() 没有通过 IDbSet 公开。我看到了一个使用扩展方法来公开 Include() 的示例代码,但它似乎对我不起作用;此示例中的 objectQuery 对象始终为空。请告诉我如何解决此问题。

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

【问题讨论】:

    标签: entity-framework-4 asp.net-mvc-3 code-first


    【解决方案1】:

    如果您使用 CTP5,则无需编写此类扩展。 CTP5 providesInclude 扩展名为IQueryable。您必须引用 EntityFramework.dll (CTP5) 并添加:

    using System.Data.Entity;
    

    您的版本可能不起作用,因为您正在将源转换为ObjectQuery,但它很可能是DbQuery 类型。

    【讨论】:

    • 一开始我没明白你在说什么。但后来我意识到我需要在我正在编写我的 linq 语句(服务类)的文件上有 using 语句来使用 Include(),而不仅仅是在我创建我的 DbContext (session.cs) 的文件上。谢谢!!!
    • 唉,对可单元测试 EF 的追求已经达到了它的目标。谢谢。
    【解决方案2】:

    确保您拥有包含上述静态类的属性using 语句。简单地复制/粘贴代码会导致 IDbSet 在引用正确的命名空间时暴露包含方法。

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 2016-04-20
      • 1970-01-01
      • 2017-02-20
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多