【问题标题】:Load related data with EF Core 3.1使用 EF Core 3.1 加载相关数据
【发布时间】:2020-04-15 20:36:36
【问题描述】:

我不确定我是否做错了,或者这是否是 EF Core 3.1 中的错误,但以下内容适用于 EF 6.x,并且是我正在转换为 EF Core 3.1 的通用存储库的一部分:

  IQueryable<TEntity> query = this.Context.Set<TEntity>();

  if (filter != null)
  {
      query = query.AsExpandable().Where(filter);
  }

  if (includeProperties != null)
  {
      foreach (var includeProperty in includeProperties.Split(new[] { ',' },
                                      StringSplitOptions.RemoveEmptyEntries))
      {
          query = query.Include(includeProperty);
      }
  }

但它在 EF Core 3.1 中不起作用

我尝试将我的“角色”属性从 virtual 更改为常规公共属性,但没有更改,奇怪的是,如果我在调用上述代码之前在数据层中调用以下代码:

var test = this.Context
               .Users
               .Include(u => u.Roles)
               .FirstOrDefault(f => f.Username == "xxx@xxx.com");

它按预期工作,然后如果我执行有问题的代码,它会按预期加载我的角色。

有什么想法吗?

谢谢

【问题讨论】:

    标签: c# entity-framework entity-framework-core linqkit


    【解决方案1】:

    更多的是LinqKit AsExpandable problem,尽管是由奇怪的 EF Core 要求引起的,即使在其 EF Core 专用版本LinqKit.Microsoft.EntityFrameworkCore 中,LinqKit 也未能/不愿意实现。

    问题在于 LinqKit 使用自己的查询提供程序,但如果查询提供程序不是他们所期望的(派生自 EntityQueryProvider 的类),EF Core 会忽略 Include 和其他一些 EF Core 可查询扩展。

    解决方法是移动所有 EF Core 特定方法,例如 IncludeThenIncludeAsNoTracking 等。之前 AsExpandable。或者根本不使用AsExpandable,在需要它的表达式上手动调用Expand(),例如而不是

        query = query.AsExpandable().Where(filter);        
    

    使用

        query = query.Where(filter.Expand());        
    

    【讨论】:

    • 工作了一个魅力!!开始转储我的通用存储库并使用特定的存储库的过程,因为我读到信息说拥有一个并不是很好而且过度杀伤力,但我必须说,我真的很喜欢我到目前为止所做的事情并且感觉不得不转储它但现在不必了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 2016-08-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多