Reputation: 1302
I want to create a one to one relationship using EF 6, code first and fluent configuration. I want the navigation property only in the root. Is this possible? If so, how do I configurate my EntityTypeConfigurations
? Do I need to change SalarayId
to EmployeeId
?
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public virtual Salary Salary {get; set; }
}
public class Salary
{
public int SalaryId { get; set; }
public double Amount { get; set; }
}
public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmployeeConfiguration()
{
HasKey(e => e.EmployeeId);
}
}
public class SalaryConfiguration : EntityTypeConfiguration<Salary>
{
public SalaryConfiguration()
{
HasKey(s => s.SalaryId);
}
}
Upvotes: 1
Views: 1104
Reputation: 34773
Yes. One-to-one relationships in EF6 are based on the PKs between the two tables. The name of the PK does not need to match, but it's generally a good idea to avoid confusion when looking at the data.
For the EntityTypeConfiguration, simply set that up from the side that has the reference to the other object, in this case Employee:
public EmployeeConfiguration()
{
HasKey(e => e.EmployeeId);
HasRequired(e => e.Salary) // or HasOptional if salary is optional on Employee
.WithRequired(); // no back reference.
}
EF should marry these up by the PK on each table.
Hopefully salary will consist of more than just a key and amount. As it stands that is unnecessary normalization. One-to-one relationships are good to accommodate things like expensive, and/or infrequently used data columns. (i.e. images or large text) Having Salary as a Double/Decimal on Employee is more efficient from a performance and storage perspective.
Upvotes: 2