【发布时间】:2012-08-14 08:13:09
【问题描述】:
我有两个 Entity Framework 5Get() 方法,它们执行 (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) 方法的逻辑编码的建议的帮助将不胜感激。
【问题讨论】:
标签: c# entity-framework-5