Linq投影嵌套LIST<;T>;所有物
本文关键字:gt 所有物 投影 lt LIST Linq 嵌套 | 更新日期: 2023-09-27 18:22:46
这个查询花了几天时间,但我几乎完成了。我已经破解了LINQ到实体的方法,通过阅读大量教程得出了以下内容。然而,我遗漏了最后一部分。
我有两个基本对象:
public class DashboardNavigation()
{
public int Id {get; set;}
public string Name {get; set;}
.....etc.....
public List<SubNav> SubDashNav {get; set;}
}
public class SubNav()
{
....properties....
}
var query = _mlsDashboardNavRepository.Table
.OrderBy(x => x.Id)
.Select(x => new
{
Id = x.Id,
Name = x.Name,
Description = x.Description,
ImageUrl = x.ImageUrl,
SubDashNav = _mlsSubDashNav.Table
.Where(s => s.DashId == x.Id)
.Select(y => new { Id = y.Id, DashId = y.DashId, Name = y.Name, Description = y.Description, ImageUrl = y.ImageUrl, IsAdvanced = y.IsAdvanced }).ToList()
}).ToList().Select(q => new MLS_DashboardNavigation()
{
Id = q.Id,
Name = q.Name,
Description = q.Description,
ImageUrl = q.ImageUrl,
SubDashNav = ...???
}).ToList();
我的Linq正确地投影了DashboardNavigation,但我不知道如何填充SubDashNav???
您不需要选择两次。我认为这也有同样的作用。
var query = _mlsDashboardNavRepository.Table
.OrderBy(x => x.Id)
.Select(x => new MLS_DashboardNavigation()
{
Id = x.Id,
Name = x.Name,
Description = x.Description,
ImageUrl = x.ImageUrl,
SubDashNav = _mlsSubDashNav.Table
.Where(s => s.DashId == x.Id).ToList()
}).ToList();
如果您使用实体框架和导航属性与DashIs作为子NavDash表的外键,那么您甚至可以执行此
var query = _mlsDashboardNavRepository.Table
.OrderBy(x => x.Id)
.Select(x => new MLS_DashboardNavigation()
{
Id = x.Id,
Name = x.Name,
Description = x.Description,
ImageUrl = x.ImageUrl,
SubDashNav = x.SubDashNav
}).ToList();
如果MLS_DashboardNavigation与_mlsDashboardNavRepository的类型相同。您甚至不需要选择表格,因为这就是返回的内容。
var query = _mlsDashboardNavRepository.Table
.OrderBy(x => x.Id).ToList()