I have following entity:
public class Revision
{
public int Id { get; set; }
...
public int? PreviousRevisionId { get; set; }
public virtual Revision PreviousRevision { get; set; }
}
What I need is to create optional-to-optional relationship within the same entity using PreviousRevision
as a navigation property and PreviousRevisionId
as a foreign key Id for it.
I know that it can be done by annotating PreviousRevisionId
property with [ForeignKey("PreviousRevision")]
attribute, but what about fluent api?
I tried:
HasOptional(c => c.PreviousRevision)
.WithOptionalDependent()
.Map(m => m.MapKey("PreviousRevisionId"));
, but doing migration I'm getting error:
PreviousRevisionId: Name: Each property name in a type must be unique. Property name 'PreviousRevisionId' is already defined.
So, basically, it looks impossible with fluent API. But I thought that annotation functionalty is a subset of fluent API functionality, isn't it?
The MapKey
is used when you don't want to have the foreign key as a property in your model class and you want to rename the FK column name that EF gives by default in your DB.
So, you have two options here:
You can map your one to one relationship as you are trying before but
you need to delete PreviousRevisionId
property:
HasOptional(c => c.PreviousRevision).WithOptionalDependent();// If you want now you can rename the FK column using .Map(m => m.MapKey("PreviousRevisionId"));
Or you can create an unidirectional one to many relationship:
HasOptional(c => c.PreviousRevision).WithMany().HasForeignKey(p => p.PreviousRevisionId);
I think the last option is more suited to what are you trying to achieve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With