来自实体框架查询的嵌套新结果

本文关键字:新结果 结果 嵌套 实体 框架 查询 | 更新日期: 2023-09-27 18:04:02

我有一个按关键字和区域过滤" inspector "的函数。"检查人员"answers"区域"之间的关系是多对多的。

public IQueryable<Inspector> Search(string keywords, int? areaId)
{
    var qry = this.GetAllInspectors();
    if (!String.IsNullOrEmpty(keywords))
       qry = qry.Search(keywords);
    if (areaId.HasValue)
       qry = qry.ByAreaId(areaId.Value);
    var search = from a in _entities.Areas
                 select new InspectorSearchResult
                 {
                     Area = i.Areas,
                     Inspectors = (.....).ToList()
                  };  // ??
    return qry.OrderBy(i => i.LastName).ThenBy(i => i.FirstName);
}

InspectorSearchResult.cs

public class InspectorSearchResult
{
    public Area Area { get; set; }
    public List<Inspector> Inspectors { get; set; }
}

我如何修改查询只得到"区域检查员"在嵌套的形式?

更新:

尝试了这个,但是得到:"…"方法不能翻译为存储表达式。"

public List<InspectorSearchResult> Search(string keywords, int? areaId)
{
       var qry = this.GetAllInspectors();
       if (!String.IsNullOrEmpty(keywords))
          qry = qry.Search(keywords);
       if (areaId.HasValue)
          qry = qry.ByAreaId(areaId.Value);
       var search = from i in qry
                    from a in i.Areas
                    orderby a.AreaName
                    select new InspectorSearchResult
                     {
                         Area = a,
                         Inspectors = (from ins in a.Inspectors
                                       orderby ins.LastName, ins.FirstName
                                       select ins).ToList()
                     };
        return search.ToList();
 } 

来自实体框架查询的嵌套新结果

这就是你想要达到的效果吗?

public List<InspectorSearchResult> Search(string keywords, int? areaId)
{
    var qry = this.GetAllInspectors();
    if (!String.IsNullOrEmpty(keywords))
        qry = qry.Search(keywords);
    if (areaId.HasValue)
        qry = qry.ByAreaId(areaId.Value);
    var search = from i in qry
        from a in i.Areas
        orderby a.AreaName
        select new InspectorSearchResult
        {
            Area = a
        };
    foreach(var x in search)
    {
        x.Inspectors = (
            from ins in a.Inspectors
            orderby ins.LastName, ins.FirstName
            select ins)
            .ToList();
    }
    return search.ToList();
}