在linq-to-sql查询中填充嵌套列表



保持简单:我想用一个列表填充一个自定义类型。

List<ParentModel> parentModelList = 
(from c in _context.children
join p in _context.parents on c.ParentId equals p.ParentId
orderby c.BirthDate
where p.GenderId = gender.GenderId // Could be a male parent or female or whatever
group c by p into childGroup
select new ParentModel()
{
ParentId = p.ParentId,
ChildList = childGroup.Select(x => new ChildModel()
{
ChildId = childGroup.Key.ChildId,
ChildName = childGroup.FirstOrDefault().ChildName,
}).ToList()
}).ToList();

你可能猜到我的问题在哪里。我不能在linq-to-Entities查询的中间调用ToList(),否则我会得到这个运行时异常:

实现IEnumerable的类型无法在LINQ to Entities查询中初始化

我正在使用EF6连接到MySql数据库,其中context是我的dbContext。以下是商店:

public class ParentModel
{
public int ParentId { get; set; }
// other properties...
List<ChildModel> ChildList { get; set; }
}
public class ChildModel
{
public int ChildId { get; set; }
public string ChildName { get; set; }
}

那么,我该如何编写这个查询以便按预期检索信息呢?我宁愿不退出手术,对结果进行预检。任何启示都将不胜感激。

它被称为Eager Loading查询。你不必进行分组,只需投影:

var query = 
from p in _context.parents
where p.GenderId = gender.GenderId // Could be a male parent or female or whatever
select new ParentModel
{
ParentId = p.ParentId,
ChildList = p.children.Select(x => new ChildModel
{
ChildId = x.ChildId,
ChildName = x.ChildName,
}).ToList()
};
var parentModelList = query.ToList();

最新更新