【问题标题】:Repository Pattern get one entity and include properties存储库模式获取一个实体并包含属性
【发布时间】:2014-09-24 15:29:43
【问题描述】:

我通过这个通用方法在 C# 中使用存储库模式和实体框架:

public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

    public virtual TEntity GetByID(object id)
    {
        return dbSet.Find(id);
    }

现在我想为 GetByID 编写一个重载来接受包含属性,就像我使用的 Get 方法一样。像这样的:

    public virtual TEntity GetByID(object id, string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;
        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }            
        return ???
    }

我应该返回什么?有什么建议吗?

【问题讨论】:

    标签: c# entity-framework repository-pattern


    【解决方案1】:

    这完全取决于您的对象——您的实体是否实现了一个声明 ID 属性的通用接口?在这种情况下,您可以query.SingleOrDefault(e =&gt; e.Id == id),但是,在似乎更有可能的情况下,您需要传入一个谓词来匹配或重新实现 Find() 功能。

    DBContext Find with Includes - where lambda with Primary keys 中,RBrowning99 从上下文中提取实体键并根据第一个键进行匹配:

    public DALEntity Get(string ID, IEnumerable<string> IncludeEntities = null)
    {
        var set = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<DALEntity>();
        var entitySet = set.EntitySet;
        string[] keyNames = entitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
    
        IQueryable<DALEntity> query = dbSet;
        query = IncludeEntities.Aggregate(query, (current, includePath) => current.Include(includePath));
    
        query = query.Where(keyNames[0] + "= @0", ID);
        return query.FirstOrDefault();
    }
    

    【讨论】:

    • hmm...他不需要一个动态的 where 子句来搜索上下文(这里完全未指定),找到并使用 pk,他已经用 'filter' 定义了他的 where 子句作为参数。他所需要的只是 query.FirstOrDefault()..
    • 实际上.. 忽略我在那里的最后评论.. 他没有通过过滤方式(在没有声明的情况下,这里似乎必须进行某种命令/反思),所以查找主键可能是值得考虑/采用的选项..
    • 方法'Where'没有重载需要2个参数
    • 虽然我没有编写引用的代码,但它可能基于动态 LINQ 扩展 --> weblogs.asp.net/scottgu/…
    猜你喜欢
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多