我有以下模型,我正在尝试从相同的父实体和子实体构建一对一以及一对多的关系。一对多关系适用于我当前的映射,但我正在努力添加新的一对一关系(对于 CoverPicture 属性)。以下是相关模型和EF映射代码:
类别.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; }
图片.cs:
public Guid Id { get; set; }
public string FileName { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
相关类别EntityTypeConfiguration<Category>
映射(不正确):
this.HasOptional(t => t.CoverPicture)
.WithRequired()
.Map(m => m.MapKey("CoverPictureId"))
.WillCascadeOnDelete(false);
相关图片EntityTypeConfiguration<Picture>
映射(正确):
this.HasRequired(t => t.Category)
.WithMany(t => t.Pictures)
.HasForeignKey(k => k.CategoryId);
当我尝试为新CoverPicture
属性添加迁移时,EF 尝试向表中添加一CoverPictureId
列Category
(这是我想要的),但也CoverPictureId
向Picture
表中添加一列(这不是我想要的;Picture
已经定义和映射了一个键)。
下面是Up()
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");
我究竟做错了什么?