Code First and EF 5.0 not loading navigation properties

前端 未结 4 917
悲&欢浪女
悲&欢浪女 2021-01-14 13:39

I am trying to load a navigation property through Code First and EF 5.0 The child object is loading as null. below is the code.

  [Table(\"ls_roles\")]
    p         


        
相关标签:
4条回答
  • 2021-01-14 14:28

    Your Role class does not need to use the ForeignKey attribute at all on the Employees collection. EF will automatically know to do the mapping based off of the ScheduleEmployee object and its use of the ForeignKey attribute.

    0 讨论(0)
  • 2021-01-14 14:29

    You have to do a .include on your calling code to include children.

    something like

    Model.ContextEntityFramework().ScheduleEmployees.Include(x => x.Role).FirstOrDefault();
    
    0 讨论(0)
  • 2021-01-14 14:31

    In order for lazy-loading to work, all properties on the class should be defined as virtual. This is required for Entity Framework to create a proxy-object that supports lazy-loading.

    See here for more information.

    0 讨论(0)
  • 2021-01-14 14:38
     [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 讨论(0)
提交回复
热议问题