Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c# - 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. I have a foreign key in the database on 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. 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.

Pay Group Table

Pay Group Table

Employee Table

Employee Table

Note: There is a foreign key from PayGroup.SupervisorId - Employee.EmployeeId in the database.

Below are the DTO's (I don't currently have any working relationship mapping between these classes):

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; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

one-to-one relationship with explicit FK property (like your PayGroup.SupervisorId) is not supported.

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. First that there is no inverse navigation property in Employee class, and second that the FK is optional (Allow Nulls = true in the table).

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).

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...