我想創建兩個屬性與關係到同一個表的表,一對一。我的模型:與同一張表一對一相關的兩個屬性
public class ImageFile : BaseEntity
{
[Key]
Guid Guid { get; set; }
public string Name { get; set; }
public string Extension { get; set; }
public long Size { get; set; }
public byte[] FileContent { get; set; }
public ProjectImage ProjectImage { get; set; }
}
public class ProjectImage : BaseEntity
{
public string Description { get; set }
public ImageFile Thumbnail { get; set; }
public ImageFile FullSizeImage { get; set; }
}
這裏是我的上下文的一部分:
modelBuilder.Entity<ProjectImage>()
.HasRequired(f => f.FullSizeImage)
.WithOptional(i => i.ProjectImage);
modelBuilder.Entity<ProjectImage>()
.HasRequired(f => f.Thumbnail)
.WithOptional(i => i.ProjectImage);
它創建數據庫中的一個一對多。爲什麼?
編輯V2:
public class ImageFile : BaseEntity
{
[Key]
Guid Guid { get; set; }
public string Name { get; set; }
public string Extension { get; set; }
public long Size { get; set; }
public byte[] FileContent { get; set; }
public Guid? ProjectImageGuid { get; set; }
[ForeignKey("ProjectImageGuid")]
public ProjectImage ProjectImage { get; set; }
}
public class ProjectImage : BaseEntity
{
public string Description { get; set }
public Guid? ThumbnailGuid { get; set; }
public Guid? FullSizeImageGuid { get; set; }
[ForeignKey("ThumbnailGuid")]
public ImageFile Thumbnail { get; set; }
[ForeignKey("FullSizeImageGuid")]
public ImageFile FullSizeImage { get; set; }
}
這裏是我的上下文的一部分:
modelBuilder.Entity<ProjectImage>()
.HasRequired(f => f.FullSizeImage)
.WithOptional(i => i.ProjectImage);
modelBuilder.Entity<ProjectImage>()
.HasRequired(f => f.Thumbnail)
.WithOptional(i => i.ProjectImage);
我有錯誤:
ProjectImage_Thumbnail_Source: : Multiplicity is not valid in Role 'ProjectImage_Thumbnail_Source' in relationship 'ProjectImage_Thumbnail'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
您無法同時在表A中使用與表B相關的主鍵和外鍵。將ImageFile的Guid屬性添加到ProjectImage並鏈接它們。 – Kami
我編輯我的問題,現在我有錯誤 – cadi2108
http://stackoverflow.com/questions/18724964/entity-framework-1-to-1-relationship-using-code-first-how檢查此 – Zergling