使用 EF Core 在 linq 中使用索引嵌套 select 投影

nested select projection with index in linq using EF Core

我刚刚修改了一个 linq 查询以包含一个索引。索引对于帮助客户端 Web 应用程序管理返回的项目(添加、删除、更新、复制等)是必需的。该部分在客户端处理模型数据,因此它需要从服务器返回的相同类型的格式结构。索引应按顺序排列为 0,1,2,..

下面是我正在尝试做的一个例子:

假设我想查找一个国家/地区的城市列表 states/provinces。

所以我有下面两个类:

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

但是我得到一个奇怪的错误:

"Could not parse expression '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 }})': This overload of the method 'System.Linq.Queryable.Select' is currently not supported."

但是,如果我取出索引,则以下内容有效:

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 does not recognize the method 'System.Linq.IQueryable`

我所要做的就是添加一个将结果转换为 C# 对象的 AsEnumerable(),然后 select(保留我原来的逻辑)将索引添加到迭代中。

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

实际上,可以使用 dbfunction row_number() over ()(至少对于 postgreSQL)简单地将 LINQ 查询转换为索引行,但目前(2021 年 2 月)仍不支持。