如何从Entity Framework中的祖父母主键获取孙子孙女

时间:2015-04-15 22:16:00

标签: entity-framework

在实体框架中,三个实体有一对多的关系,如祖父母,子女和孙子女。如何获得给予祖父母主键的所有孙子的对象列表?

谢谢,

Newby to EF

1 个答案:

答案 0 :(得分:0)

如果这三个实体之间有两个一对多的关系,我想你可以这样做:

int grandparentId=1;
using(var ctx=new YourContext())
{
  var grandparent=ctx.GrandParents.FirstOrDefault(gp=>gp.Id==grandparentId);
  if(grandparent!=null)
  {
    // a list with all the grandchildren
    var grandchildren=grandparent.Children.SelectMany(c=>c.GrandChildren).ToList();
  }
}

而且,如果您没有使用延迟加载,那么您需要使用Include扩展方法:

int grandparentId=1;
using(var ctx=new YourContext())
{
  var grandparent=ctx.GrandParents.Include(gp=>gp.Children.Select(c=>c.GrandChildren)).FirstOrDefault(gp=>gp.Id==grandparentId);
  if(grandparent!=null)
  {
    // a list with all the grandchildren
    var grandchildren=grandparent.Children.SelectMany(c=>c.GrandChildren).ToList();
  }
}

但是,正如@ErikPhilips所说,您需要提供有关您的模型的更多信息。没有这些信息,很难对你的真实问题给出具体的答案。

相关问题