【问题标题】:Entity Framework Core: many-to-many relationship between generic object tablesEntity Framework Core:通用对象表之间的多对多关系
【发布时间】: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

标签: c# entity-framework-core


【解决方案1】:

EF Core 还没有一些更复杂的关系处理(例如分层)。

在您的特定示例中,您可以使用

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;}
}

在 EF 6 中,您可以让 Animal、Dog 和 Cat 都进入不同的桌子。 EF 会为您设置按键和导航字段。对象的类型(狗/猫)将控制您将看到的 Animal 中的哪些记录。请注意,这是一对一关系(分层)的特殊情况。

您提到了多对多,但我发现两种动物不太可能共享相同的图像,如果跨物种名称重复是一个问题,请将名称移至派生类(狗/猫)。

在某些时候 EF Core 可能会这样做,我只是还没有看到它(DataAnnotation/Fluent)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多