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

点点圈 提交于 2019-12-12 12:29:10

问题


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?


回答1:


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"));


来源:https://stackoverflow.com/questions/12092061/ef-5-0-code-first-two-way-navigation-withought-foreign-key-id-in-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!