c# - 使用 EF Core 在 linq 中使用索引的嵌套选择投影
问题描述
我刚刚修改了一个 linq 查询以包含一个索引。索引对于帮助客户端 Web 应用程序管理返回的项目是必要的(添加、删除、更新、复制等)。该部分在客户端处理模型数据,因此它需要从服务器返回的相同类型的格式结构。索引应按 0,1,2,.. 排序
下面是我正在尝试做的一个例子:
假设我想查找一个国家/地区的城市列表,该国家/地区拥有州/省。
所以我有以下两个类:
public class CityItemDTO {
public int id { get; set; }
public City item {get; set; }
}
public class CityDTO {
public string name {get; set;}
public string stateName {get; set; }
public int population {get; set; }
}
我想将索引与城市和州属性列表一起添加:
var cities = context.Countries
.Where(s => query.Name == s.Name)
.Select((s,index) => new CityItemDTO
{
id = index,
item = new CityDTO()
{
name = s.name,
stateName = s.stateName
population = s.population
}
});
但我得到一个奇怪的错误:
“无法解析表达式'value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[DataService.Models.Countries]).Where(s => (__query_Name_0 == s.Name)).Select((s, index) => new CityItemDTO() {id = index, item = new CityDTO() {Name = s.Name, StateName = s.StateName, Population = s.Population }})':方法 'System.Linq 的重载。当前不支持 Queryable.Select'。”
但是,如果我取出索引,则以下工作:
var cities = context.Countries
.Where(s => query.Name == s.Name)
.Select(s => new CityDTO
{
new CityDTO()
{
name = s.name,
stateName = s.stateName
population = s.population
}
});
解决方案
显然这个问题之前已经回答过了,因为新的框架,错误信息是不同的,而且因为我是如何得到答案的,认为预测会干扰索引器的工作方式。
LINQ to Entities 无法识别方法“System.Linq.IQueryable”
我所要做的就是添加一个 AsEnumerable() ,它将结果转换为 C# 对象,然后选择(保留我最初拥有的逻辑)然后将索引添加到迭代中。
var cities = context.Countries
.Where(s => query.Name == s.Name)
.AsEnumerable() // where the magic happens
.Select(s => new CityDTO
{
new CityDTO()
{
name = s.name,
stateName = s.stateName
population = s.population
}
});
推荐阅读
- azure - 无法通过 RDP 连接到 Azure 虚拟机
- bixby - 使用 EL 作为布局宏表达式的参数
- python - 在 Python 中,为什么我的 for 循环仅在特定数字之前的数字是数组中的最后一个数字时才排除该数字?
- networking - 您可以在法定人数中混合服务器品牌吗?
- sql - SQL Server 日期时间说明
- php - 表字段将 VARCHAR 记录为 0
- mysql - 如何在两个表之间插入关系,其中确定的数据集与主键相关?
- swift - 如何打印数组的偶数总和/平均和奇数总和/平均?
- .net - 保护桌面应用程序和 Web API 之间的通信
- bash - 如何在 bash 中使用 getopts 并让它与额外的标志一起使用?