2つのEntityFramework5 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 Framework5を使用してTEntityGetById(int id、IEnumerable includePaths)メソッドのロジックをコーディングする方法の提案に関するヘルプをいただければ幸いです。