[英]Entity Framework Core and including child collections
本質上,我想做的是查詢父實體的子級集合。 根據EF Core文檔,我可以使用Include
和ThenInclude
方法來做到這一點( https://docs.microsoft.com/en-us/ef/core/querying/related-data )。 因此,我在存儲庫中有以下代碼來獲取所需的數據:
public object GetMatchupByVideoId(int id)
{
var videoMatchup = _DBContext.Matchups
.Where(m => m.VideoID == id)
.Include(m => m.Players).ThenInclude(p => p.Character)
.Include(m => m.Players).ThenInclude(p => p.User);
return videoMatchup;
}
這段代碼實際上是在尋找與傳遞的id
相匹配的Matchups
實體。 然后,它退出並包含Players
集合,該集合是模型上的導航屬性。 返回的數據如下所示:
[
{
"id": 1,
"players": [
{
"id": 1,
"user": {
"id": 1,
"displayName": "Player 1"
},
"character": {
"id": 40,
"name": "Superman"
},
"outcome": 0
},
{
"id": 2,
"user": {
"id": 2,
"displayName": "Player 2"
},
"character": {
"id": 43,
"name": "Batman"
},
"outcome": 1
}
]
}
]
這一切都很好,但是它給了我更多的數據,而不是我真正感興趣的數據。例如,我希望我的user
屬性只具有displayName
屬性的值。 除此之外,這就是我想要的數據結構,我只想更改某些屬性。
到處尋找答案,我發現有些人建議使用SelectMany
。 因此,當我將代碼重新排列為:
public object GetMatchupByVideoId(int id)
{
var videoMatchup = _DBContext.Matchups
.Where(m => m.VideoID == id)
.SelectMany(m => m.Players, (parent, child) => new { parent, child })
.Select(pc => new {
players = pc.child
});
return videoMatchup;
}
返回的數據如下所示:
[
{
"players": {
"id": 1,
"user": null,
"character": null,
"outcome": 0
}
},
{
"players": {
"id": 2,
"user": null,
"character": null,
"outcome": 1
}
}
]
這有一些缺點。 首先是沒有相關數據的加載和它們是兩個不同的對象players
時,它應該只是一個收藏。
因此,我有幾個問題,我相信它們都與相同的答案有關:
Include
情況下查詢子數據? 我很難相信這是唯一的方法。 SelectMany
方法將對象協調為一個列表,就像返回的第一個數據結構一樣? 我懷疑所有提出的問題都與一個答案有關。 搜索並處理完之后,可以按照以下方法完成此操作:
public object GetMatchupByVideoId(int id)
{
var videoMatchup = _DBContext.Matchups
.Where(m => m.VideoID == id)
.Select(m => new {
ID = m.VideoID,
Players = m.Players.Select(p => new {
ID = p.PlayerID,
User = p.User,
Character = p.Character,
Outcome = p.Outcome
})
});
return videoMatchup;
}
SelectMany
在這里不是正確的方法。 您想要使用的是Select
並使用子項列表之外的投影。 這回答了我提出的以下問題:
只需使用Select
方法將子列表投射到導航屬性中即可。
SelectMany
方法將對象協調為一個列表,就像返回的第一個數據結構一樣? 在這種情況下,您不SelectMany
因為SelectMany
用於展平列表列表。
與第一個答案相同。
與第一個答案相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.