[英]Entity Framework returns null for Include properties
我有3個具有多對多連接的實體(表):
public class AccUserRole
{
public long Id { get; set; }
public string RoleName { get; set; }
public List<AccAdGroup> Groups { get; set; }
public List<AccScreen> Screens { get; set; }
}
public class AccAdGroup
{
public long Id { get; set; }
public string AdIdent { get; set; }
public List<AccUserRole> Roles { get; set; }
}
public class AccScreen
{
public long Id { get; set; }
public string ScreenIdent { get; set; }
public List<AccUserRole> Roles { get; set; }
}
我想獲得至少有一個指定的組列表(當前用戶的組)的所有角色(包括他們的屏幕和組)。 所以我使用了這個查詢:
List<AccUserRole> userRoles = (from ur in db.AccUserRoles.Include("Groups").Include("Screens")
from g in ur.Groups
where user.Groups.Contains(g.AdIdent)
select ur).ToList();
它獲得了正確的角色,但Groups
和Screens
屬性為null。 看起來像EF具有:使用問題Include
和第二from
。 任何有關如何包含屬性或重寫查詢的幫助將不勝感激。
渴望加載
這樣做的原因是您只指定了一個包含級別,而您的查詢是在第二級別請求某些內容。
您的include允許您詢問ur.Groups
和ur.Screens
。 下一個級別from g in ur.Groups
,並且您沒有包含該級別。 (這對您來說可能是意料之外的,因為您已經在查詢的第一部分中詢問了所有AccUserRoles
。)
要使您的查詢運行,您可以在開始時添加另一個.include
,深入兩個級別:
from ur in db.AccUserRoles
.Include("Groups")
.Include("Groups.Roles")
.Include("Screens")
如果你需要進入另一個級別,你只需添加另一個包括:
from ur in db.AccUserRoles
.Include("Groups")
.Include("Groups.Roles")
.Include("Groups.Roles.Groups")
.Include("Screens")
...等等。
如果你有很多級別要嵌套,這可能會變得很麻煩,所以另一種方法是使用延遲加載 ,正如Praval的Shaun'Tirubeni建議的那樣,通過將virtual
關鍵字添加到實體中的集合。
在ToList()
之前移動include。
select ur).Include("Groups").Include("Screens").ToList();
子選擇可以刪除Include
效果。
如果您正在進行急切加載,則不需要virtual
關鍵字。 通過添加virtual
,您使用延遲加載,而不是急切加載。
嘗試將虛擬關鍵字添加到類屬性中,如下所示:
public class AccUserRole
{
public long Id { get; set; }
public string RoleName { get; set; }
public virtual List<AccAdGroup> Groups { get; set; }
public virtual List<AccScreen> Screens { get; set; }
}
public class AccAdGroup
{
public long Id { get; set; }
public string AdIdent { get; set; }
public virtual List<AccUserRole> Roles { get; set; }
}
public class AccScreen
{
public long Id { get; set; }
public string ScreenIdent { get; set; }
public virtual List<AccUserRole> Roles { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.