我有两个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();
}
随着应用程序的增长,现在所有这些都可以正常工作,我发现我正在编写许多需要两者混合的非泛型方法 - 更具体地说,我想要一个通用的通过 ID 获取并且还能够急切加载相关实体。
所以方法签名看起来像这样:
public TEntity GetById(
int id,
IEnumerable<string> includePaths)
{
// ???
}
我可以这样称呼:
User user = UnitOfWork.UserRepository.GetById(117, new List<string>() { "UserRole", "UserStatus" });
或者像这样:
Car car = UnitOfWork.CarRepository.GetById(51, new List<string>() { "Make", "Model", "Tyres" });
任何有关我如何使用 Entity Framework 5 为TEntity GetById(int id, IEnumerable includePaths)方法的逻辑编码的建议的帮助将不胜感激。