我有这个仓库,
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly DbContext context;
private readonly DbSet<TEntity> dbEntitySet;
public Repository(DbContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
this.dbEntitySet = context.Set<TEntity>();
}
public IEnumerable<TEntity> GetAll()
{
return this.dbEntitySet;
}
public IEnumerable<TEntity> GetAll(string include)
{
return this.dbEntitySet.Include(include);
}
public IEnumerable<TEntity> GetAll(string[] includes)
{
foreach (var include in includes)
this.dbEntitySet.Include(include);
return this.dbEntitySet;
}
public void Create(TEntity model)
{
this.dbEntitySet.Add(model);
}
public void Update(TEntity model)
{
this.context.Entry<TEntity>(model).State = EntityState.Modified;
}
public void Remove(TEntity model)
{
this.context.Entry<TEntity>(model).State = EntityState.Deleted;
}
public void Dispose()
{
this.context.Dispose();
}
}
我遇到的问题是这种方法:
public IEnumerable<TEntity> GetAll(string[] includes)
{
foreach (var include in includes)
this.dbEntitySet.Include(include);
return this.dbEntitySet;
}
当我运行它并在返回之前放置一个断点时,就好像 foreach 被忽略了。
上面的方法效果很好:
public IEnumerable<TEntity> GetAll(string include)
{
return this.dbEntitySet.Include(include);
}
要调用它,我基本上是这样做的:
var a = this.Repository.GetAll(new string[] { "ForbiddenUsers", "ForbiddenGroups" }).ToList();
这会拉回结果但不包含包含 :D 如果我将调用修改为:
var a = this.Repository.GetAll("ForbiddenUsers").ToList();
它工作正常。
有人能给我一个解决方案吗?
最佳答案
将您的方法更改为如下所示:
public IEnumerable<TEntity> GetAll(string[] includes)
{
var query = this.dbEntitySet;
foreach (var include in includes)
query = query.Include(include);
return query;
}
Include
方法不会改变 DbSet
,它只会返回一个新的 DbQuery
和您的 include。
关于c# - 为什么 EF 预加载包含不按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21142862/