EF 5.0 Code First Two way navigation withought foreign key id in child

 

Questions


I have following classes

public class Employer
{
    [Key]
    public Int64 EmployerID { get; set; }
    public String CompanyName { get; set; }
    public virtual List<Employee> Employees { get; set; }
}

public class Employee
{
    [Key]
    public Int64 EmployeeID { get; set; }
    public String EmployeeName { get; set; }
    public virtual Employer EmployerInfo { get; set; }
}

In the Database context I have set the relation as

modelBuilder.Entity<Employer>()
.HasMany(p => p.Employees)
.WithRequired()
.Map(x => x.MapKey("EmployerID"));

After executing some actions, database gets created with Employee table having EmployerID as foreign key and one extra key EmployerInfo_EmployerID.

Now when I fetch employer data, I am getting employee details with it.
But when I tried to fetch employee data I am getting EmployerInfo as null. This is because I need relationship from Employee to EmployerInfo.

How do I set the bi-directional relationship in this context?

 

 

————————————————-

Answer

You need to update your fluent so your relationship mapping contains both ends:

        modelBuilder.Entity<Employer>()
        .HasMany(p => p.Employees)
        .WithRequired(e => e.EmployerInfo)
        .Map(x => x.MapKey("EmployerID"));

ef-code-first,entity-framework

Facebook Comments

Post a comment