我的课程是这样的:
public class ParentModel
{
public int ID { get; set; }
public string ParentName { get; set; }
public List<ChildModel> ChildModel { get; set; }
}
public class ChildModel
{
public int ParentID { get; set; }
public string ChildName { get; set; }
}
我就是这样使用的。
List<ParentModel> parentModel = new List<ParentModel>();
using(MyEntities db = new MyEntities())
{
foreach(Parent parent in db.Parents.Where(some_condition_here))
{
parentModel.Add (
new ParentModel {
ID = parent.ID,
ParentName = parent.ParentName
}
);
}
}
问题是我不知道如何将子记录添加到每个父记录中。似乎无法为其构建语法。如何将子记录包含在每条父记录中?
假设您与子实体有 FK 关系,我在这里将其称为
ChildEntities
,所以就这样做
var parents = db.Parents
.Where(some_condition_here)
.Include(x => x.ChildEntities)
.ToAray();
然后
foreach (var parent in parents)
{
parentModel.Add(new ParentModel
{
ID = parent.ID,
ParentName = parent.ParentName,
ChildModel = parent.ChildEntities
.Select(x => new ChildModel
{
ParentId = parent.Id,
ChildName = x.Name,
})
.ToArray(),
});
}