EF通用存储库多个包含 [英] EF Generic Repository Multiple Includes
问题描述
想法将有一个通用存储库,它将与所有实体一起使用。
我设法做到了,但是如果我需要一种应该包含一个或多个其他实体的方法,那对我来说就是个问题。
我已经在代码中添加了一些想法,但这对我不起作用。
我也一直在考虑在EF中使用聚合函数,但是我从未使用过。有人可以给我指导我如何管理它吗?
Idea is to have one Generic Repository which will work with all entities. I managed that, but if I need to have method which should include one or more other entities there is a problem for me. I have put some idea in code, but that is not working for me. Also I have been thinking to use aggregate function in EF, but that I have never use. Can someone give me direction how I can manage this ?
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();
}
}
推荐答案
您陷入了调用方法返回结果并忽略结果的典型陷阱。 entities.Include(include);
行不执行任何操作-与 entities.Where(...);
类似, entities.Select(...);
等。
You have fallen in the typical trap of calling a method which returns something and ignoring the result. The line entities.Include(include);
does nothing - similar to entities.Where(...);
, entities.Select(...);
etc.
正确的代码是这样的:
var query = entities.AsQueryable();
foreach (var include in includes)
query = query.Include(include);
return query;
或使用单行 汇总
:
or with single line Aggregate
:
return includes.Aggregate(entities.AsQueryable(), (query, path) => query.Include(path));
这篇关于EF通用存储库多个包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!