Code First和EF 5.0无法加载导航属性

3

我正在尝试通过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


什么确切地作为 null 载入了? - Corey Adler
哪个“子级”属性是空的?Role还是Employees - Steven V
当您查看ScheduleEmployee对象时,角色返回为空。 - gh9
如果该角色是必需的,那么您不应该将其设置为虚拟的。不确定是否会阻止它。可能不会。 - Thewads
我去掉了虚拟的部分,但仍然返回 null。 - gh9
4个回答

8
为了使惰性加载生效,应将类中的所有属性定义为虚拟。这是必须的,以便Entity Framework创建支持惰性加载的代理对象。
更多信息请参见此处

我更新了我的回答,并附上了官方文档的链接,列出了EF生成代理所需的所有要求。 - w.brian

7
你需要在调用代码中执行 .include 命令以包含子项。
类似于以下内容:
Model.ContextEntityFramework().ScheduleEmployees.Include(x => x.Role).FirstOrDefault();

感谢您指引我正确的方向。最终使其工作的代码是var z = new Model.ContextEntityFramework().ScheduleEmployees.Include("Role").FirstOrDefault(); - gh9
include会导致导航属性被急切加载,这并不一定是坏事,但对于许多情况来说绝对不是理想的选择。正确的解决方案是使延迟加载正常工作。 - w.brian
当前环境下懒加载不是一个选项。 - gh9

1

您的 Role 类不需要在 Employees 集合上使用 ForeignKey 属性。EF 会根据 ScheduleEmployee 对象及其使用 ForeignKey 属性来自动进行映射。


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; }
}

请您能否添加一些代码描述,特别是它如何以及为什么解决了这个问题? - Cleb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接