![](/img/trans.png)
[英]Related many to one navigation properties not loading with EF code first
[英]Code First and EF 5.0 not loading navigation properties
我試圖通過Code First和EF 5.0加載導航屬性子對象加載為null。 下面是代碼。
[Table("ls_roles")]
public class Role
{
[Required]
[Key]
public int RoleID { get; set; }
[Required]
public String BarColor { get; set; }
[ForeignKey("RoleId")]
public virtual ICollection<ScheduleEmployee> Employees { get; set; }
}
[Table("ls_ScheduleEmployee")]
public class ScheduleEmployee
{
[Key]
[Required]
public int Id { get; set; }
[Required]
public int RoleId { get; set; }
[ForeignKey("RoleId")]
public Role Role { get; set; }
}
編輯:調用代碼
class Program
{
static void Main(string[] args)
{
var x = new Model.ContextEntityFramework().ScheduleEmployees.FirstOrDefault();
}
}
x.Role ==此時為null
為了使延遲加載工作,應該將類的所有屬性定義為虛擬。 這是Entity Framework創建支持延遲加載的代理對象所必需的。
有關更多信息,請參見此處
您必須對您的主叫代碼執行.include以包含子項。
就像是
Model.ContextEntityFramework().ScheduleEmployees.Include(x => x.Role).FirstOrDefault();
您的Role
類不需要在Employees
集合上使用ForeignKey
屬性。 EF將自動知道根據ScheduleEmployee
對象及其對ForeignKey
屬性的使用進行映射。
[Table("ls_roles")]
public class Role
{
[Required]
[Key]
public int RoleID { get; set; }
[Required]
public String BarColor { get; set; }
public virtual ICollection<ScheduleEmployee> Employees { get; set; }
}
[Table("ls_ScheduleEmployee")]
public class ScheduleEmployee
{
[Key]
[Required]
public int Id { get; set; }
[Required]
[ForeignKey("Role")]
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.