代码之家  ›  专栏  ›  技术社区  ›  LukLed

实体框架和存储库模式问题

  •  6
  • LukLed  · 技术社区  · 16 年前

    我将通用存储库模式用于方法:

        private ObjectQuery<T> ObjectQueryList()
        {
            var list = CamelTrapEntities.CreateQuery<T>(EntitySetName);
            return list;
        }
    

        public IQueryable<T> List()
        {
            return ObjectQueryList();
        }
    

    metod list()返回iqueryable<t>,因为iqueryable<t>易于模拟。我也有扩展方法:

        public static IQueryable<T> Include<T>(this IQueryable<T> obj, string path)
        {
            if (obj is ObjectQuery<T>)
                (obj as ObjectQuery<T>).Include(path);
    
            return obj;
        }
    

    此方法在存储库外部用于获取已加载导航属性的实体列表,例如:list.include(“createdby”)。问题是它不起作用。忽略所有包含。当我将list()方法更改为

        public ObjectQuery<T> List()
        {
            return ObjectQueryList();
        }
    

    一切正常。

    如何实现存储库模式才能执行更复杂的查询?

    3 回复  |  直到 14 年前
        1
  •  6
  •   LukLed    16 年前

    反射器给了我一个答案:

    public ObjectQuery<T> Include(string path)
    {
        EntityUtil.CheckStringArgument(path, "path");
        return new ObjectQuery<T>(base.QueryState.Include<T>((ObjectQuery<T>) this, path));
    }
    

    include返回新的objectquery对象,my include函数返回旧对象。改为

    public static IQueryable<T> Include<T>(this IQueryable<T> obj, string path)
    {
        if (obj is ObjectQuery<T>)
            return (obj as ObjectQuery<T>).Include(path);
    
        return obj;
    }
    

    解决了这个问题。几个小时过去了,我更讨厌实体框架:)

    它还让我意识到,我应该创建另一个包含include参数的列表函数,而不允许在存储库之外执行include操作。

        2
  •  1
  •   Dave Swersky    16 年前

    Here 是我见过的最全面的ef存储库模式实现。我不能确定它是否允许您执行include(),但如果我正确地阅读了实现,它应该会执行。

        3
  •  1
  •   Boris Nikolaevich    14 年前

    对于EntityFramework4.1,dbextensions( System.Data.Entity.DbExtensions )解决了这个问题,并在本机中添加了 .Include([string path]) .Include([property expression]) 对于任何 IQueryable<T> .

    只需确保使用存储库的项目引用entityframework,并与任何扩展方法一样,指定 using System.Data.Entity; 在类文件中访问这些扩展名。

    推荐文章