使用包含检索实体的通用存储库和实体框架逻辑

Ber*_*ern 5 c# entity-framework-5

我有两个Entity Framework 5 Get()方法,它们执行(i)单个实体获取ID,以及(ii)单个实体通过过滤器获得任何急切加载螺栓.请参阅下面的代码:

internal readonly FallenNovaContext Context;
private readonly DbSet<TEntity> _dbSet;

internal GenericRepository(FallenNovaContext context)
{
    Context = context;
    _dbSet = context.Set<TEntity>();
}

// (i) Get by ID.
public TEntity GetById(int id)
{
    return _dbSet.Find(id);
}

// (ii) Get by filter and optional eager loading includes.
public TEntity Get(
    Expression<Func<TEntity, bool>> filter = null,
    IEnumerable<string> includePaths = null)
{
    IQueryable<TEntity> query = _dbSet;

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

    if (includePaths != null)
    {
        query = includePaths.Aggregate(query, (current, includePath) => current.Include(includePath));
    }

    return query.SingleOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

所有这些工作正常,我发现随着我的应用程序的增长,我正在编写许多非泛型方法,需要两者兼而有之 - 更具体地说,我想要一个通用的ID,并且能够加载相关实体.

所以方法签名看起来像这样:

 public TEntity GetById(
     int id,
     IEnumerable<string> includePaths)
 {
       // ???
 }
Run Code Online (Sandbox Code Playgroud)

我可以这样打电话:

 User user = UnitOfWork.UserRepository.GetById(117, new List<string>() { "UserRole", "UserStatus" });
Run Code Online (Sandbox Code Playgroud)

或者像这样:

 Car car = UnitOfWork.CarRepository.GetById(51, new List<string>() { "Make", "Model", "Tyres" });
Run Code Online (Sandbox Code Playgroud)

关于如何使用Entity Framework 5来编写TEntity GetById(int id,IEnumerable includePaths)方法的逻辑的建议的任何帮助将不胜感激.

dar*_*yal 2

首先,为实体编写一个基类,定义主键字段。像下面这样的东西可能会起作用:

public abstract class BaseEntity
{
    public int Id {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

然后,为您的存储库编写一个基类;在此基础存储库中定义所有通用方法。让这个存储库有一个实体类型的通用参数:

public class RepositoryBase<TEntity> where TEntity : BaseEntity
{
   public TEntity GetById(
     int id,
     params Expression<Func<TEntity, object>>[] includeList)
     {
            TEntity entity = null;
            ObjectQuery<TEntity> itemWithIncludes = context.Set<TEntity>() as ObjectQuery<TEntity>;
            foreach (Expression<Func<TEntity, object>> path in includeList)
            {
                itemWithIncludes = ((IQueryable)itemWithIncludes.Include(path)) as ObjectQuery<T>;
            }

            IQueryable<TEntity> items = itemWithIncludes.AsQueryable<TEntity>();
            entity = items.Where(p => p.Id == id).SingleOrDefault();
            return entity;
     }
}
Run Code Online (Sandbox Code Playgroud)

更新:@Bern 询问除了声明基类之外是否还有其他方法来查找主键。以下问题涉及这个问题。

实体框架4:如何查找主键?

首先是实体框架代码。查找主键

另一方面,我不知道 EF 5 中是否还有其他方法。