首页 > 解决方案 > 使用 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
        }
    });

标签: c#linqasp.net-coreef-core-2.0

解决方案


显然这个问题之前已经回答过了,因为新的框架,错误信息是不同的,而且因为我是如何得到答案的,认为预测会干扰索引器的工作方式。

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
    }
});

推荐阅读