【问题标题】:IQueryable.Union/Concat in .net core 3.net 核心 3 中的 IQueryable.Union/Concat
【发布时间】:2021-02-11 20:18:13
【问题描述】:

我想向 IQueryable 添加一个虚拟成员并提出了以下解决方案:

IQueryable<Geography> geographies = _unitOfWork.GeographyRepository.GetAll(); //DbSet<Geography>

var dummyGeographies = new Geography[] { new Geography { Id = -1, Name = "All" } }.AsQueryable();

var combinedGeographies = geographies.Union(dummyGeographies);

var test = combinedGeographies.ToList(); //throws runtime exc

但它会抛出以下异常:

处理 LINQ 表达式 'DbSet .Union(EnumerableQuery { Geography, })' by 'NavigationExpandingExpressionVisitor' 失败。这可能表示 EF Core 中存在错误或限制。

我怎样才能让它工作?!

【问题讨论】:

  • var combinedGeographies = geographies.ToList().Union(dummyGeographies).ToList();?
  • 内存列表和数据库表不能合并,需要切换到客户端求值

标签: linq asp.net-core iqueryable


【解决方案1】:
  1. 你只能联合相同的数据结构
  2. IQueryable 仅适用于查询表达式在针对 db 运行之前未表示 (ToList) 并且您希望表达式 modifiable 。也就是没有任何不作为查询的 db 需要是 IQueryable 的(简单的解释更好地自己研究和理解)
List<Geography> geographies = _unitOfWork.GeographyRepository
                        .GetAll()  //DbSet<Geography>
                        .Select(o => new Geography { Id = o.Id, Name = o.Name })
                        .ToList();

List<Geography> dummyGeographies = new List<Geography>() { 
                                        new Geography[] { new Geography { Id = -1, Name = "All" } }
                                    };

var combinedGeographies = geographies.Union(dummyGeographies);

var test = combinedGeographies.ToList(); 

【讨论】:

    【解决方案2】:

    我可以通过以下代码实现它:

    IQueryable<Geography> geographies = _unitOfWork.GeographyRepository.GetAll().Select(o => new Geography { Id = o.Id, Name = o.Name });
    
    IQueryable<Geography> dummyGeographies = _unitOfWork.GeographyRepository.GetAll().Select(o => new Geography { Id = -1, Name = "All" });
    
    var combinedGeographies = geographies.Union(dummyGeographies);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 2017-08-05
      • 1970-01-01
      • 2019-11-15
      • 2016-07-23
      • 1970-01-01
      相关资源
      最近更新 更多