代码之家  ›  专栏  ›  技术社区  ›  sksallaj

使用EF核的linq中带索引的嵌套select投影

  •  2
  • sksallaj  · 技术社区  · 6 年前

    我刚刚修改了一个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
            }
        });
    

    但我有一个奇怪的错误:

    “无法分析表达式的值(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable ` 1[数据服务.模型.国家])。其中(s=>(\uu Query\u Name\u 0==s.Name))。选择((s,index)=>new CityItemDTO(){id=索引,item=new CityTo(){Name=s.Name,StateName=s.StateName,Population=s.Population}”})“:此方法重载”系统。林克。可查询。当前不支持“选择”。“”

    但是,如果我将索引取出,以下内容将起作用:

    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
            }
        });
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   sksallaj    6 年前

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

    LINQ to Entities does not recognize the method 'System.Linq.IQueryable`

    我所要做的就是添加一个AsEnumerable(),将结果转换为C#对象,然后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
        }
    });
    
        2
  •  -1
  •   iPilot    4 年前

    实际上,LINQ查询可以简单地转换为索引行,其中dbfunction row\u number()over()(至少对于postgreSQL)但目前(2021年2月)仍然不受支持。