I have the following model and I am trying to construct a one-to-one and also one-to-many relationships from the same parent and child entities. The one-to-many relationship works with my current mappings but I am struggling with adding the new one-to-one relationship (for CoverPicture property). Here are the relevant model and EF mapping codes:
Category.cs:
public int Id { get; set; }
public string Name { get; set; }
public Guid? CoverPictureId { get; set; }
public virtual Picture CoverPicture { get; set; }
public virtual ICollection<Picture> Pictures { get; set; }
Picture.cs:
public Guid Id { get; set; }
public string FileName { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
Relevant Category EntityTypeConfiguration<Category>
mappings (incorrect):
this.HasOptional(t => t.CoverPicture)
.WithRequired()
.Map(m => m.MapKey("CoverPictureId"))
.WillCascadeOnDelete(false);
Relevant Picture EntityTypeConfiguration<Picture>
mappings (correct):
this.HasRequired(t => t.Category)
.WithMany(t => t.Pictures)
.HasForeignKey(k => k.CategoryId);
When I try to add a migration for the new CoverPicture
property, EF tries to add a CoverPictureId
column to the Category
table (which is what I want) but also CoverPictureId
to the Picture
table (which is not what I want; Picture
already has a key defined and mapped).
Here is the Up()
migration code scaffolded by EF:
AddColumn("dbo.Category", "CoverPictureId", c => c.Guid());
AddColumn("dbo.Picture", "CoverPictureId", c => c.Int());
CreateIndex("dbo.Picture", "CoverPictureId");
AddForeignKey("dbo.Picture", "CoverPictureId", "dbo.Category", "Id");
What am I doing wrong?