简体   繁体   中英

How to Use The Same Table With Different Entities In EF6

I have entity DbDropPhoto with navigation property

public class DbDropPhoto
{
    public virtual DbContour Contour { get; set; }
}

public class DbContour
{
    public virtual DbDropPhoto CurrentDropPhoto { get; set; }
}

Relationship configured like this using FluentAPI:

    modelBuilder.Entity<DbContour>()
        .HasRequired(s => s.CurrentDropPhoto)
        .WithOptional(s => s.Contour)
        .WillCascadeOnDelete();

now I need to add same DbContour entity to another entity called DbThermalPhoto. What is the best way to do it. Should I create separate table for example DbThermalPhotoContour or I can somehow re-use existing table. I've searched for similar questions but solution to them seemed to be very complicated.

I managed to achieve it like this:

        modelBuilder.Entity<DbDropPhoto>()
            .HasOptional(c => c.Contour)
            .WithMany()
            .HasForeignKey(s => s.ContourId);

        modelBuilder.Entity<DbThermalPhoto>()
            .HasOptional(c => c.Contour)
            .WithMany()
            .HasForeignKey(s => s.ContourId);

And Entities:

[Table("DropPhotos")]
public class DbDropPhoto
{
    [Key] public Guid PhotoId { get; set; }

    public Guid? ContourId { get; set; }

    [ForeignKey("ContourId")]
    public virtual DbContour Contour { get; set; }
}

[Table("ThermalPhotos")]
public class DbThermalPhoto
{
    [Key] public Guid PhotoId { get; set; }

    public Guid? ContourId { get; set; }

    [ForeignKey("ContourId")]
    public virtual DbContour Contour { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM