![](/img/trans.png)
[英]C# - Using Entity Framework Core 3 HasConversion to convert a field to JSON in .Net Core 3.1
[英]C# .NET Core 3.1 Entity Framework : include using where condition gives wrong output
我有 2 個實體父/子想要 select 他們都使用包含。
在孩子上添加條件時,它會返回僅具有此條件的父母,而不是所有父母
我的代碼:
父實體:
public class SecRole
{
public string Name { get; set; }
public virtual ICollection<SecRolePageAction> SecRole_SecRolePageAction { get; set; }
}
子實體:
public class SecRolePageAction
{
public virtual SecRole SecRole { get; set; }
public long SecRoleID { get; set; }
public bool IsDeleted { get; set; } = false;
}
代碼:
var Q = Context.Set<SecRole>().AsNoTracking().AsQueryable();
Q = Q.Include(O => O.SecRole_SecRolePageAction)
// Child condition below
.Where(O => O.SecRole_SecRolePageAction.Any(P => P.IsDeleted == false)
.ToList();
結果:它只返回父包含子有IsDeleted = false
但任何父沒有子它不返回
我需要回報所有父母的任何幫助
看起來您正在正確選擇和包含。 您可能只需要修改您的 Where 子句來檢查您的子集合是否為空/空,或者它是否有任何未刪除的子集合。
就像是:
.Where(O => O.SecRole_SecRolePageAction.Count() == 0 || O.SecRole_SecRolePageAction.Any(P => P.IsDeleted == false))
@Keith.Abramo alreay給出了這個問題的正確答案。
這是此解決方案的測試結果。
public List<SecRole> getSecRole()
{
var SecRoles = _context.SecRoles.Include(h => h.SecRole_SecRolePageAction)
.Where(O => O.SecRole_SecRolePageAction.Count() == 0 || O.SecRole_SecRolePageAction.Any(P => P.IsDeleted == false)).ToList(); // include address table
return SecRoles;
}
SecRoles
的日期來源:
[
{
"Name": "1",
"SecRole_SecRolePageAction": [
{
"SecRoleID": "101",
"IsDeleted": "true"
}
]
},
{
"Name": "2",
"SecRole_SecRolePageAction": [
]
},
{
"Name": "3",
"SecRole_SecRolePageAction": [
{
"SecRoleID": "301",
"IsDeleted": "false"
},
{
"SecRoleID": "302",
"IsDeleted": "true"
}
]
}
]
測試結果截圖與
Where
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.