If I defined (in code first) one navigation property to self it works (foreign key is created), but if I define 2 it doesn't work.
How can I create 2 foreign keys to self? Based on documentation by conventions they should be created.
For example this works (foreign key is created):
public class DbPart
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("Source")]
public int? SourceId { get; set; }
public DbPart Source { get; set; }
[InverseProperty("Source")]
public List<DbPart> SourceParts { get; set; }
}
and so is this:
public class DbPart
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("SourceFake")]
public int? SourceFakeId { get; set; }
public DbPart SourceFake { get; set; }
[InverseProperty("SourceFake")]
public List<DbPart> SourceFakeParts { get; set; }
}
but not this:
public class DbPart
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("Source")]
public int? SourceId { get; set; }
public DbPart Source { get; set; }
[ForeignKey("SourceFake")]
public int? SourceFakeId { get; set; }
public DbPart SourceFake { get; set; }
[InverseProperty("SourceFake")]
public List<DbPart> SourceFakeParts { get; set; }
[InverseProperty("Source")]
public List<DbPart> SourceParts { get; set; }
}
I also have another example, where I write tree structure in database, but instead writing just ParentId, I also write RootId. Again, foreign key is not created when referencing 2 properties to self (ParentId, RootId).
Edited:
It is not working because of this bug. Easy solution is to remove [Key] from Id property or use fluent solution in Steve Greene answer. Check also here.