I am trying to establish a One-to-Zero-or-One relationship between two entities and I want the dependent entity to still contain its own Indentity column, instead of it being a
Bidirectional one-to-one
relationship with explicit FK property is not supported.
So either continue using what you have now - Shared Primary Key association. Just get rid of one of the TaskId
or FileId
properties from Task
and make the remaining a PK (EF will automatically use it as FK because that's the default EF one-to-one
relationship model).
Or get rid of the FieldId
property from Task
and use the following fluent configuration (all is necessary):
modelBuilder.Entity()
.HasOptional(f => f.Task)
.WithRequired(t => t.File)
.Map(m => m.MapKey("FileId"))
.WillCascadeOnDelete();
But I would recommend using the first approach (if there is no special reason of not doing it like existing database etc.) because it's better supported - the second includes some LEFT OUTER JOIN
s in SQL queries as you can see from this post EF - WithOptional - Left Outer Join?.