How to define nested Identifying Relationships Entity Framework code first

前端 未结 1 1144
傲寒
傲寒 2021-01-03 04:19

I\'m using EF5 code first in a simple test application at the moment to test various functions. I have defined an \'identifying relationship\' between two entities which rep

1条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 04:32

    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 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()
        .HasMany(pc => pc.Photos)
        .WithRequired(p => p.Parent)
        .HasForeignKey(p => p.PhotoCollectionId);
    
    modelBuilder.Entity()
        .HasKey(p => new { p.PhotoCollectionId, p.PhotoId });
    
    modelBuilder.Entity()
        .Property(p => p.PhotoId)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    
    modelBuilder.Entity()
        .HasMany(p => p.PhotoProperties)
        .WithRequired(pp => pp.Parent)
        .HasForeignKey(pp => new { pp.PhotoCollectionId, pp.PhotoId });
    
    modelBuilder.Entity()
        .HasKey(pp => new { pp.PhotoCollectionId, pp.PhotoId, pp.PhotoPropertyId });
    
    modelBuilder.Entity()
        .Property(pp => pp.PhotoPropertyId)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    

    0 讨论(0)
提交回复
热议问题