[英]One to One Relationship with Different Primary Key in EF 6.1 Code First
I am having an issue getting a reference to the employee object from the PayGroup object using Entity Framework 6.1. 我在使用实体框架6.1从PayGroup对象获取对雇员对象的引用时遇到问题。 I have a foreign key in the database on PayGroup.SupervisorId -> Employee.EmployeeId. 我在PayGroup.SupervisorId-> Employee.EmployeeId上的数据库中有一个外键。 Note that this is a zero or one-to-one relationship (a pay group can only have one supervisor and an employee can only be the supervisor of one pay group). 请注意,这是零关系或一对一关系(一个薪资组只能有一个主管,而一个雇员只能是一个薪资组的主管)。
According to this post on GitHub , it is not possible to have a foreign key on a table with a different primary key. 根据GitHub上的这篇文章 ,不可能在具有不同主键的表上具有外键。 I've added the foreign key to the database manually but I can't figure out how to set up the fluent api mapping to be able to get the employee object from pay group. 我已将外键手动添加到数据库中,但是我不知道如何设置流利的api映射以能够从工资组中获取雇员对象。
Pay Group Table 工资组表
Employee Table 员工表
Note: There is a foreign key from PayGroup.SupervisorId - Employee.EmployeeId in the database. 注意:数据库中有一个来自PayGroup.SupervisorId-Employee.EmployeeId的外键。
Below are the DTO's (I don't currently have any working relationship mapping between these classes): 以下是DTO(我目前在这些类之间没有任何工作关系映射):
public class PayGroup
{
public int Id { get; set; }
public string SupervisorId { get; set; }
public virtual Employee Supervisor { get; set; }
}
public class Employee
{
public string EmployeeId { get; set; }
public string FullName { get; set; }
}
one-to-one
relationship with explicit FK property (like your PayGroup.SupervisorId
) is not supported. 不支持具有显式FK属性(例如PayGroup.SupervisorId
) one-to-one
关系。
So remove that property from the model: 因此,从模型中删除该属性:
public class PayGroup
{
public int Id { get; set; }
public virtual Employee Supervisor { get; set; }
}
and use the following fluent mapping: 并使用以下流利的映射:
modelBuilder.Entity<PayGroup>()
.HasRequired(e => e.Supervisor)
.WithOptional()
.Map(m => m.MapKey("SupervisorId"));
The WithOptional()
call specifies two things. WithOptional()
调用指定了两件事。 First that there is no inverse navigation property in Employee
class, and second that the FK is optional ( Allow Nulls = true
in the table). 首先,在Employee
类中没有反向导航属性,其次,FK是可选的(表中Allow Nulls = true
)。
If you decide to add inverse navigation property 如果您决定添加反向导航属性
public class Employee
{
public string EmployeeId { get; set; }
public string FullName { get; set; }
public virtual PayGroup PayGroup { get; set; } // <=
}
change it to WithOptional(e => e.PayGroup)
. 将其更改为WithOptional(e => e.PayGroup)
。
If you want to make it required ( Allow Nulls = false
in the table), then use the corresponding WithRequiredDependent
overload ( Dependent here means that the Employee
will be the principal and PayGroup
will be the dependent ). 如果要使其成为必需项(表中Allow Nulls = false
),则使用相应的WithRequiredDependent
重载(“ Dependent”在这里表示Employee
将是委托人,而PayGroup
将是从属 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.