2017-07-26 53 views
0

想法是有一個通用知識庫將與所有實體一起工作。 我管理的,但如果我需要有方法應該包括一個或多個其他實體對我來說是一個問題。 我已經在代碼中提出了一些想法,但這不適合我。 另外我一直在考慮在EF中使用聚合函數,但我從來沒有使用過。有人能指導我如何管理這個嗎?EF通用知識庫多個包含

public interface IRepository<T> where T : BaseEntity 
    { 
     IEnumerable<T> GetAll(); 
     T Get(Int64 id); 
     void Insert(T entity); 
     void Delete(T entity); 
     Task<bool> SaveChangesAsync(); 
     T SearchByName(Expression<Func<T, bool>> predicate); 
     IEnumerable<T> GetAll(string[] includes); 

    } 



public class Repository<T> : IRepository<T> where T : BaseEntity 
    { 
     private Entities.AppContext _context; 
     private DbSet<T> entities; 

     public Repository(Entities.AppContext context) 
     { 
      _context = context; 
      entities = _context.Set<T>(); 
     } 

     public void Delete(T entity) 
     { 
      if (entity == null) 
      { 
       throw new ArgumentNullException("entity"); 
      } 
      entities.Remove(entity); 
     } 

     public T Get(long id) 
     { 
      return entities.SingleOrDefault(s => s.Id == id); 
     } 

     public IEnumerable<T> GetAll() 
     { 
      return entities.ToList(); 
     } 

     public IEnumerable<T> GetAll(string[] includes) 
     { 
      foreach (string include in includes) 
      { 
       entities.Include(include); 
      } 
      return entities; 
     } 

     public void Insert(T entity) 
     { 
      if (entity == null) 
      { 
       throw new ArgumentNullException("entity"); 
      } 
      entities.Add(entity); 
     } 

     public async Task<bool> SaveChangesAsync() 
     { 
      try 
      { 
       return (await _context.SaveChangesAsync()) > 0; 
      } 
      catch (Exception ex) 
      { 

       return false; 
      } 

     } 

     public T SearchByName(Expression<Func<T, bool>> predicate) 
     { 
      return entities.Where(predicate).SingleOrDefault(); 
     } 
    } 

回答

4

您已經下降在調用返回的東西的方法,而忽略結果的典型陷阱。 entities.Include(include);什麼都不行 - 類似entities.Where(...);entities.Select(...);

正確的代碼是這樣的:

var query = entities.AsQueryable(); 
foreach (var include in includes) 
    query = query.Include(include); 
return query; 

或使用單線Aggregate

return includes.Aggregate(entities.AsQueryable(), (query, path) => query.Include(path));