如何在LINQ中向父列表中添加多个子记录

hivapdat  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(152)

我的课是这样的:

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
         }
      );
   }
}


问题是我不知道如何将子记录添加到每个父记录中。似乎无法为它构造语法。我如何将子记录包含到每个父记录中?

sbdsn5lh

sbdsn5lh1#

假设你有FK关系到子实体,我在这里只称之为ChildEntities,所以只要做

var parents = db.Parents
    .Where(some_condition_here)
    .Include(x => x.ChildEntities)
    .ToArray();

字符串
然后

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(),
    });
}

相关问题