EF 4.1 one to one Mapping
I have two tables Employees and Positions.
Employee
EmployeeId (PK)
PositionId (FK, Nullable)
开发者_如何学JAVAPosition
PositionId (PK)
A position can be created and not be assigned. However, an active employee requires a position. A position can only be assigned to one employee. We enforce this by having a Unique Constraint on Employee.PositionId.
In my models, I want to have an Employee property in Position and I am having issues mapping this.
I've tried
modelBuilder.Entity<Employee>().HasRequired(e => e.Position)
.WithOptional(p => p.Employee);
However this ends up mapping the Employee.EmployeeId to Position.PositionId column, instead of Employee.PositionId to Position.PositionId (at least from what I can tell...)
Is my only option to make map this as a One to Many relationship even though I am forcing 1-1 through unique constraint?
Quoting from: http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key-associations.aspx
Code First (and EF in general) does not natively support one-to-one foreign key associations. In fact, EF does not support any association scenario that involves unique constraints at all.
In fluent api:
modelBuilder.Entity<Employee>()
.HasRequired(e => e.Position)
.WithMany()
.HasForeignKey(e => e.PositionId);
Then override the Seed
method:
protected override void Seed(EntityMappingContext context)
{
context.Database.SqlCommand("ALTER TABLE Employees ADD CONSTRAINT uc_Position UNIQUE(PositionId)");
}
精彩评论