我正在嘗試在 EF Core 中使用過濾的包含,但遇到了一個我似乎無法確定具體原因的問題。
我的查詢看起來像這樣:
context.Users.Include(u=>u.UserRoles.Where(r => r.Role.Category == 3))
.ThenInclude(r=>r.Role).Where(u => u.userId == currentUserId)
.Select(u=> new UserDTO()
{
UserDisplayName= u.Name,
ListOfRoles = String.Join(",", u.UserRoles.Select(u => u.Role.DisplayName))
}).FirstOrDefaultAsync();
如果我從查詢中省略 Select 部分并檢查物件,它只填充了適當的 UserRoles,屬于類別 3 的那些,但是在檢查此 Select 的結果時,它還包含屬于不同的角色類別,連接到 ListOfRoles。
如果有人知道可能導致這種情況的原因,我將不勝感激。
謝謝
uj5u.com熱心網友回復:
Include僅適用于您回傳物體的情況。當您使用投影時,Select您需要過濾Select運算式中的資料:
context.Users
.Where(u => u.userId == currentUserId)
.Select(u=> new UserDTO()
{
UserDisplayName= u.Name,
ListOfRoles = String.Join(",", u.UserRoles
.Where(ur => ur.Role.Catecory == 3)
.Select(ur => ur.Role.DisplayName))
}).SingleOrDefaultAsync();
我相信 String.Join 需要在 EF Core 中進行客戶端評估。這可能會導致加載意外資料。避免這種情況的建議是在 DTO 內執行串聯,以便 Linq 查詢加載原始資料并可以有效地將其轉換為 SQL:
context.Users
.Where(u => u.userId == currentUserId)
.Select(u=> new UserDTO()
{
UserDisplayName= u.Name,
Roles = u.UserRoles
.Where(ur => ur.Role.Catecory == 3)
.Select(ur => ur.Role.DisplayName))
.ToList();
}).SingleOrDefaultAsync();
在 DTO 中,您將擁有:
[Serializable]
public class UserDTO
{
public string UserDisplayName { get; set; }
public IList<string> Roles { get; set; } = new List<string>();
public string ListOfRoles
{
get { return string.Join(",", Roles); }
}
}
這確保查詢可以高效運行并完全轉換為 SQL,然后將格式移動到 DTO。
uj5u.com熱心網友回復:
Include僅當您直接選擇物體時才有效。一旦你做了投影(Select例如)Include就會被忽略。您可以嘗試在串聯部分應用類別過濾:
context.Users
.Where(u => u.userId == currentUserId)
.Select(u=> new UserDTO()
{
UserDisplayName= u.Name,
ListOfRoles = String.Join(",", u.UserRoles.Where(r => r.Role.Category == 3).Select(u => u.Role.DisplayName))
})
.FirstOrDefaultAsync();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/340471.html
上一篇:WebGL著色器渲染小游戲實戰
