Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF6.1 optional-to-optional with fluent api mapping

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?

like image 316
drty Avatar asked Sep 27 '22 22:09

drty


1 Answers

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.

like image 95
octavioccl Avatar answered Sep 30 '22 06:09

octavioccl