2013-03-11 102 views
3

我想通过Code First和EF 5.0加载导航属性子对象加载为null。下面是代码。Code First和EF 5.0无法加载导航属性

[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在这一点上

+0

什么是加载为null? – IronMan84 2013-03-11 15:46:20

+0

哪个是“孩子”属性是null? 'Role' or'Employees' – 2013-03-11 15:46:55

+0

如果角色是必需的,那么当您查看scheduleemployee对象 – gh9 2013-03-11 15:47:48

回答

7

您必须对您的调用代码执行.include以包含子项。

Model.ContextEntityFramework().ScheduleEmployees.Include(x => x.Role).FirstOrDefault(); 
+0

谢谢你指出我在正确的方向。使这项工作的代码最终成为var z = new Model.ContextEntityFramework()。ScheduleEmployees.Include(“Role”)。FirstOrDefault(); – gh9 2013-03-11 16:00:14

+0

包含导致导航属性被急切加载,这并不一定是坏的,但绝对不适合很多情况。正确的解决方案是延迟加载工作。 – 2013-03-11 16:13:59

+0

懒惰加载不是在当前环境中的一个选项 – gh9 2013-03-11 21:11:00

1

Role类并不需要在所有使用ForeignKey属性上Employees集合。 EF将自动根据ScheduleEmployee对象及其对ForeignKey属性的使用情况进行映射。

8

为了让懒加载工作,在类的所有属性应该被定义为虚拟的。这是实体框架创建支持延迟加载的代理对象所必需的。

查看here了解更多信息。

+0

不知道,你可以给我一个链接,你发现在那里。谢谢!!!! – gh9 2013-03-11 16:07:47

+0

我通过官方文档的链接更新了我的答案,该链接列出了EF生成代理的所有要求。 – 2013-03-11 16:13:10

0
[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; } 
} 
+0

请问您可以添加一些关于您的代码的描述,特别是如何以及为何解决这个问题! – Cleb 2015-11-19 14:12:13