c# - 为什么 EF 预加载包含不按预期工作?

标签 c# entity-framework eager-loading

我有这个仓库,

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/

相关文章:

c# - 几个小时后并行发送 HTTP 请求后 ServicePoint 对象的大小很大

c# - 使用字节作为主键数据类型

c# - EF急切加载导航属性问题

c# - 为什么——如何——在处理后处理交易?

c# - Visual Studio 调试器未附加

asp.net - EF、UoW 和存储库 - 何时在 WebForms 中处理 UnitOfWork?

entity-framework - 具有列序号 <> 主键序号的 Entity Framework 复合键定义

eloquent - Laravel Eager Loading 在单个注入(inject)模型上

laravel - 当急切加载一个belongsToMany 关系时,如何链接->makeHidden()?

c# - 如何手动反序列化 ModelStateDictionary