Reputation: 15771
I am trying to figure out how to make this work in EF. I have two entities Employee
and User
. I need to make it so the User
has an optional mapping to the Employee
. If there is a mapping, then it would be 1:1.
Basically this system can be accessed by employees and also by outside vendors, but I want one table to manage logons: Users
.
How do I define this realtionship in EF with fluid configurations?
Upvotes: 1
Views: 1152
Reputation: 4458
public class User
{
...
public virtual Employee Employee { get; set; }
}
This tutorial may help.
Upvotes: 1
Reputation: 364259
You just need to set simple fluent configuration:
modelBuilder.Entity<User>()
.HasOptional(u => u.Employee)
.WithRequired(e => e.User);
or in reverse order:
modelBuilder.Entity<Employee>()
.HasRequired(e => e.User)
.WithOptional(u => u.Employee);
EF will use Employess's PK as FK to user - that is mandatory requirement for EF to correctly use one-to-one relation. In case of Data annotation it is enough to mark Employee's PK with ForeignKey
attribute pairing it with User
navigation property:
public class Employee {
[Key, ForeignKey("User")]
public int Id { get; set; }
public virtual User User { get; set; }
}
Upvotes: 3