.net 核心 3 中的 IQueryable.Union/Concat

IQueryable.Union/Concat in .net core 3

我想向 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

但它抛出以下异常:

Processing of the LINQ expression 'DbSet .Union(EnumerableQuery { Geography, })' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core.

我怎样才能让它发挥作用?!

我能够通过以下代码实现它:

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);
  1. 只能对相同的数据结构进行联合
  2. IQueryable 仅适用于查询表达式在其 运行 针对 db 之前未被表达 (ToList) 且您希望表达式可修改的情况。也就是不会作为查询进行数据库查询的任何东西都不需要是可查询的(简单的解释更好地自己研究和理解)
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();