此查询花了几天时间,但我几乎就在那里。我已经通过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 ???
答案 0 :(得分:1)
您无需选择两次。我认为这也是一样的。
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作为subNavDash表的外键,那么您甚至可以这样做
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.Table的类型相同,那么您甚至不需要选择,因为它仍然是返回的。
var query = _mlsDashboardNavRepository.Table
.OrderBy(x => x.Id).ToList()