[英]Entity Framework Core: Get parent with all child entities where exists a child with specific criteria
我有一個包含子列表的父實體。
public class Parent
{
public int Id { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Type { get; set; }
}
EFcore 將在表Child
中創建一個ParentId
作為外鍵。
假設我有幾個具有不同Type
字符串的子實體。 我想檢索包括所有子實體的父實體,而不考慮Type
字符串(即“Alpha”、“Beta”、“Charlie”等)。 但首先,我想根據特定的Type
字符串過濾子實體,類似於 SQL 查詢中的exists
。
select * from Parent inner join Child ON Parent.Id = Child.ParentId
where exists (select * from Parent where Parent.Id = Child.ParentId AND Type = 'Alpha')
如何使用 EFCore 實現這一目標?
您可以使用Any()
:
_dbContext.Parents
.Include(p => p.Children)
.Where(p => p.Children.Any(c => String.Equals(c.Type, "Alpha")))
.ToList(); // or use await and ToListAsync()
因此它查詢至少有一個類型等於Alpha
的孩子的父母(包括孩子)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.