给定 child 时如何显示祖父母

How to display grandparent when child is given

如何在给定 'childItemNo' 时显示 grandparent。

以下是我的模型:任何记录 (ItemNo) 都可以成为一个 grandparent、parent 或 child.

public partial class item
{      
    public string ItemNo { get; set; }         
    public string ParentItemNo { get; set; }     
}

下面的查询 returns parent 当 childItemNo 给定时:也想显示 grandparent。

  var result =  DbContext.ItemTables.Where(p => p.ItemNo== childItemNo).Select(p => p.ParentItemNo).ToListAsync(); 

谢谢。

如果您有导航属性,这很简单:

Select(c => c.Parent.ParentItemNo)

没有它们,你可能会变得更脏:

Select(c => DbContext.ItemTables.First(p => p.ItemNo == c.ParentItemNo).ParentItemNo)

或使用连接

(from ch in db.ItemTables
join pa in db.ItemTables
on ch.ParentItemNo equals pa.ItemNo
where ch.ItemNo == childItemNo
select pa.ParentItemNo).First()

或者在方法语法中:

db.ItemTables.Where(ch => ch.ItemNo == childItemNo).Join(
  db.ItemTables,
  l => l.ParentItemNo, //left is the child
  r => r.ItemNo,       //right is the parent
  (l, r) => r.ParentItemNo  //want the parent's parent
).First();