給出“childItemNo”時如何顯示祖父母。
下面是我的模型:任何記錄(ItemNo)都可以成為祖父母、父母或孩子。
public partial class item
{
public string ItemNo { get; set; }
public string ParentItemNo { get; set; }
}
下面的查詢在給定 childItemNo 時回傳父級: 也想顯示祖父級。
var result = DbContext.ItemTables.Where(p => p.ItemNo== childItemNo).Select(p => p.ParentItemNo).ToListAsync();
謝謝你。
uj5u.com熱心網友回復:
如果您有導航屬性,這很簡單:
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/476611.html
