抱歉我的英文。我有以下实体:
public class MediaAlbum
{
[Key]
public Guid AlbumId { get; set; }
public string Title { get; set; }
public virtual ICollection<MediaImage> Images { get; set; }
public Guid? CoverId { get; set; }
[ForeignKey("ImageId")]
public virtual MediaImage Cover { get; set; }
}
public class MediaImage
{
[Key]
public Guid ImageId { get; set; }
public string Image { get; set; }
public Guid AlbumId { get; set; }
[ForeignKey("AlbumId")]
public virtual MediaAlbum Album { get; set; }
}
我需要地图导航属性封面到实体&#39; MediaImage&#39;。 我试图通过fluentApi解决,但它没有用:
modelBuilder.Entity<MediaAlbum>().HasOptional(x => x.Cover).WithOptionalPrincipal()
.Map(x => x.MapKey("ImageId"));
答案 0 :(得分:1)
使用它:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MediaAlbum>().HasMany(x => x.Images)
.WithRequired(x => x.Album).HasForeignKey(x=>x.AlbumId);
modelBuilder.Entity<MediaAlbum>().HasOptional(x => x.Cover);
}
外键是CoverId
而不是ImageId
:
public class MediaAlbum
{
[Key]
public Guid AlbumId { get; set; }
public string Title { get; set; }
public virtual ICollection<MediaImage> Images { get; set; }
public Guid? CoverId { get; set; }
[ForeignKey("CoverId")]// change to this
public virtual MediaImage Cover { get; set; }
}
答案 1 :(得分:0)
试试这个:
modelBuilder.Entity<MediaAlbum>()
.HasOptional(x => x.Cover)
.WithRequired(x => x.Album)
.WillCascadeOnDelete();