How to define nested Identifying Relationships Entity Framework code first

馋奶兔 提交于 2019-11-30 14:53:05

In my opinion this should work:

public class Photo
{
    [Key, ForeignKey("Parent"), Column(Order = 1)]
    public int PhotoCollectionId { get; set; }

    [Key, Column(Order = 2)]
    public int PhotoId { get; set; }

    public virtual PhotoCollection Parent { get; set; }

    public virtual ISet<PhotoProperty> PhotoProperties { get; private set; }

    //...
}

public class PhotoProperty
{
    [Key, ForeignKey("Parent"), Column(Order = 1)]
    public int PhotoCollectionId { get; set; }

    [Key, ForeignKey("Parent"), Column(Order = 2)]
    public int PhotoId { get; set; }

    [Key, Column(Order = 3)]
    public int PhotoPropertyId { get; set; }

    public virtual Photo Parent { get; set; }

    //...
}

Note that PhotoCollectionId in PhotoProperty doesn't refer to a PhotoCollection but is part of the composite foreign key (PhotoCollectionId,PhotoId) that refers to Photo.

And yes, you can define the whole mapping with Fluent API:

modelBuilder.Entity<PhotoCollection>()
    .HasMany(pc => pc.Photos)
    .WithRequired(p => p.Parent)
    .HasForeignKey(p => p.PhotoCollectionId);

modelBuilder.Entity<Photo>()
    .HasKey(p => new { p.PhotoCollectionId, p.PhotoId });

modelBuilder.Entity<Photo>()
    .Property(p => p.PhotoId)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

modelBuilder.Entity<Photo>()
    .HasMany(p => p.PhotoProperties)
    .WithRequired(pp => pp.Parent)
    .HasForeignKey(pp => new { pp.PhotoCollectionId, pp.PhotoId });

modelBuilder.Entity<PhotoProperty>()
    .HasKey(pp => new { pp.PhotoCollectionId, pp.PhotoId, pp.PhotoPropertyId });

modelBuilder.Entity<PhotoProperty>()
    .Property(pp => pp.PhotoPropertyId)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!