2017-07-26 10 views
0

アイデアは、すべてのエンティティで動作する1つの汎用リポジトリを持つことです。 私はそれを管理しましたが、1つまたは複数の他のエンティティを含めるべき方法が必要な場合は、私にとって問題があります。 私はいくつかの考えをコードに入れましたが、それは私のためには機能しません。 また、私は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

あなたは何かを返し、結果を無視する典型的な方法を呼び出すトラップには慣れていません。

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

またはAggregateの1行を持つ:

return includes.Aggregate(entities.AsQueryable(), (query, path) => query.Include(path)); 
- 何もしません entities.Include(include);ライン entities.Where(...);と同様に、 entities.Select(...);など

正しいコードは次のようなものです

関連する問題