问题
I have a Cat and Dog table and I want to create many-to-many relationships to an Image table. I don't want to create a join table for every table (DogImage, CatImage, BirdImage, etc) so I figured I would create a single EntityImage join table and then use a Type field to know what type of image it is. Here is my attempt at the model below, however this creates CatId, DogId, etc foreign keys in the EntityImage table, instead of using the EntityId I tried to define. Does anyone know how to handle this properly with the latest Entity Framework Core? Thanks!
public class Cat
{
[Key] public int CatId { get; set; }
public string CatName { get; set; }
public ICollection<EntityFile> Files { get; } = new List<EntityFile>();
}
public class Dog
{
[Key] public int DogId{ get; set; }
public string DogName { get; set; }
public ICollection<EntityImage> Images { get; } = new List<EntityImage>();
}
public class Image
{
[Key] public int ImageId { get; set; }
public string ImageName{ get; set; }
public Byte[] Content { get; set; }
}
public class EntityImage
{
public int EntityId { get; set; }
public int ImageId { get; set; }
public int ImageType { get; set; }
public Image Image { get; set; }
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<EntityImage>().ToTable("EntityImage").HasKey(t => new { t.EntityId, t.ImageId });
}
回答1:
EF Core doesn't have some of the more sophisticated relationship handling (e.g. hierarchical) yet.
In your particular example, you could just use
public class Animal {
public string Name {get; set;}
public byte[] Image {get; set;}
}
public class Cat : Animal {
public int Id {get; set;}
}
public class Dog : Animal {
public int Id {get; set;}
}
In EF 6, you could have Animal, Dog & Cat all go to different tables. EF would set up the keys & navigation fields for you. The type of object (Dog/Cat) would control which records in Animal you would see. Note that this is a specialized case of one-to-one relationship (hierarchical).
You mentioned many to many, but I find it not very likely that two animals share the same image and if duplication of Name across species is an issue, move Name to the derived classes (Dog/Cat).
At some point EF Core will probably do this, I just haven't seen it yet (DataAnnotation/Fluent).
来源:https://stackoverflow.com/questions/50646600/entity-framework-core-many-to-many-relationship-between-generic-object-tables