【发布时间】:2018-06-01 15:20:20
【问题描述】:
我有一张 Cat 和 Dog 表,我想创建与 Image 表的多对多关系。我不想为每个表(DogImage、CatImage、BirdImage 等)创建一个连接表,所以我想我会创建一个 EntityImage 连接表,然后使用一个类型字段来知道它是什么类型的图像。这是我对下面模型的尝试,但是这会在 EntityImage 表中创建 CatId、DogId 等外键,而不是使用我尝试定义的 EntityId。有谁知道如何使用最新的 Entity Framework Core 正确处理这个问题? 谢谢!
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 });
}
【问题讨论】:
-
使用 Dog 和 Cat 继承的 Animal 表(阅读:Dog 和 Cat 的主键 = 动物的外键),并在 Animal 和 Image 之间创建连接表。
-
然后,为了识别某种动物,我会让 Cat 和 Dog 拥有主键/外键 animalId,以及 Animal 表中的 AnimalKind 列,让您的应用程序知道它是哪种动物.这种解决方案并不完美(允许动物在 db 中同时成为猫和狗),但不幸的是,任何解决方案在这种情况下都有缺陷。
-
有趣的想法,但是我只是用动物作为例子来解释这个问题。我的真实表可能相关也可能不相关,从公共类继承可能有意义也可能没有意义。
-
但显然,它们确实有一些共同点,它们都与图像相关联。即使它很模糊,这还不足以证明某些基类 "EntityWithImages" 的合理性吗?
-
有关使用 EF 表示某些继承的方法的信息:learnentityframeworkcore.com/inheritance