First双向导航小孩的外键ID

First双向导航小孩的外键ID

本文介绍了EF 5.0 Code First双向导航小孩的外键ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程

  public class Employer 
{
[Key]
public Int64 EmployerID {get;组; }
public String CompanyName {get;组; }
public virtual List< Employee>员工{get;组;
}

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

在数据库上下文中,我将关系设置为

$ ()
.HasMany(p => p.Employees)
.WithRequired()
.Map(x => x.MapKey(EmployerID));

执行一些操作后,使用Employee表创建数据库,具有 EmployerID 作为外键和一个额外的键 EmployerInfo_EmployerID



现在,当我提取雇主数据时,我我得到员工的细节。
但是当我尝试获取员工数据时,我将EmployerInfo作为空值。这是因为我需要从员工到雇主信息的关系。



如何在此上下文中设置双向关系?

解决方案

你需要更新你的流利,所以你的关系映射包含两端:

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


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?

解决方案

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 5.0 Code First双向导航小孩的外键ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 19:01