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
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.
You have to do a .include on your calling code to include children.
something like
Model.ContextEntityFramework().ScheduleEmployees.Include(x => x.Role).FirstOrDefault();
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.
[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; }
}