我正在使用 EF Core 并陷入需要獲取具有與給定子記錄匹配的子記錄的所有父表記錄的場景。例子:
父表
| ID | 姓名 |
|---|---|
| 1 | P1 |
| 2 | P2 |
| 3 | P3 |
子表
| ID | 父 ID | 姓名 | 年齡 | 地址 |
|---|---|---|---|---|
| 1 | 1 | C1 | 20 | 美國廣播公司 |
| 2 | 1 | C2 | 25 | xyz |
| 3 | 2 | C1 | 20 | |
| 4 | 2 | C2 | 25 | 韋爾 |
| 5 | 3 | C3 | 30 | 秋 |
我需要 Linq 來獲取所有匹配以下搜索引數的父母。
所有具有 Child 記錄的 prents 相同: Child: [ {C1,20}, {C2,25}]
因此,它應該回傳父 P1 和 P2 作為結果。我正在嘗試 EqualityComparer 但未從 EF 獲得翻譯錯誤。任何幫助表示贊賞。
uj5u.com熱心網友回復:
我不認為 EF 支持這一點。遇到同樣的情況(子表上的多列主鍵),我沒有找到直接的解決方案。我的解決方法是將人工(計算 存盤)字串列添加到組合所有 PK 部分的子表中,之后您應該能夠執行以下操作:
var childrenKeys = new List<string>();
/* .... fill it with children keys you are interested in ... */
var parents = dbContext.Parents
.Where(x => x.Children.Any(xx => childrenKeys.Contains(xx.NameAndAge))
.ToList();
我知道的唯一其他選擇是切換到客戶端評估并自己過濾。
uj5u.com熱心網友回復:
編輯:我改變了我的答案,因為你的評論為我提供了我沒有的資訊。我相信你可能正在尋找這個:
var childrenConditions = new List<Child>()
{
new Child()
{
Name = "C1",
Age = 20
},
new Child()
{
Name = "C2",
Age = 25
},
}
var children = context.Children.Include(child => child.Parent);
var groupedChildren = children.GroupBy(child => child.Parent.Id);
var rightParents = new List<Parent>();
foreach(var group in groupedChildren)
{
var respectsConditions = true;
foreach(var condition in childrenConditions)
{
if ((group.Select(child =>
child.Name != condition.Name ||
child.Age != condition.Age)).Any())
{
respectsConditions = false;
break;
}
}
if (respectsCondition)
{
rightParents.Add(group.First().Parent);
}
}
在演算法結束時,“rightParents”將是一個包含您正在搜索的父母的集合。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510714.html
標籤:C#林克实体框架核心
