如何根据属性查询TEntity?

时间:2018-08-06 02:01:21

标签: c# entity-framework linq

我有基于传递的ID对该数据库集的查询

public TEntity Get(int id)
{
    return Context.Set<TEntity>().Find(id);
}

然后我意识到有时候我需要重新加载其属性,所以我添加了一个重载

public TEntity Get(int id, string includeProperties)
{

    IQueryable<TEntity> query = Context.Set<TEntity>().AsQueryable();
    foreach (var includeProperty in includeProperties.Split
    (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
    {
        query = query.Include(includeProperty);
    }

    return query.Single(i => i.) //I don't know this part here
}

我想做return query.Single(i => i.Id == id),但不起作用。

i.Id中说

  

“ TEntity不包含ID的定义”,因为它是通用实体。

1 个答案:

答案 0 :(得分:0)

尝试一下

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
   protected readonly YourDbContext _context;
   public Repository(YourDbContext DbContextScope)  //Intitalizing DBContext
   {
     if(DbContextScope == null)
     {
        throw new ArgumentNullException("DbContextScope");
     }
     _context = DbContextScope.Create();
   }
 public TEntity FindSingleEager(Expression<Func<TEntity, bool>> predicate, List<string> paths)
 {
     var query = _context.Set<TEntity>().Where(predicate);
     foreach (string path in paths)
     {
       query = query.Include(path);
     }
     return query.SingleOrDefault<TEntity>();
  }
}

您可以这样称呼

var yourRepository  = new YourRepository(YourDbcontextScope);
var res = yourRepository
          .FindSingleEager(i => i.Id == id , new List<string>() { "Path1","Path2" ,"Path3"});
  

您可以修改存储库以创建您的dbcontext,而不是通过传递instance来创建它,这是您的选择。