存储库模式获取一个实体并包含属性

时间:2014-09-24 15:29:44

标签: c# entity-framework repository-pattern

我在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 写一个重载来接受includeproperties,就像我使用的获取方法一样。像这样:

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

我应该归还什么?有什么建议吗?

1 个答案:

答案 0 :(得分:2)

这完全取决于您的对象 - 您的实体是否实现了声明ID属性的公共接口?在那种情况下,您可以query.SingleOrDefault(e => 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();
}