【问题标题】:How can a common "Attachments" table can be linked to several tables in Entity Framework Core?一个常见的“附件”表如何链接到 Entity Framework Core 中的多个表?
【发布时间】:2017-08-17 11:31:48
【问题描述】:

我有几个实体,我想提供存储文件的可能性。就像对于给定的客户,存储其身份证或产品的副本,存储其进口文件和质量证书。

我不希望将这些文件存储在相同的实体行中,并且我为附件创建了一个单独的表。解耦它还可以让我稍后决定是否要直接存储文件、存储位置或某些 CMS 访问令牌。

那么,我如何在 EF 中建立此附件表和可能具有该功能的所有其他表之间的这种关系?

架构示例:

public class Customer
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Product
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Attachment
{
    [Key]
    public int Id { get; set; }
    //Relation property
    public int ParentId { get; set; }
    public string Name { get; set; }
    public byte[] Content { get; set; }
}

【问题讨论】:

  • 添加public Attachment Attachment { get; set;}到你的班级,你有什么困惑?
  • 你的意思是public virtual ICollection<Attachment> Attachments { get; set; }?这样做的问题是它没有通过“ParentId”连接表,然后它确实在附件表中为每个链接表创建了一个 CustomerId、ProductId...一个字段。
  • 作为跨表唯一的 guid,应该是一种解决与目标表中的一个字段的关系的方法。还是我错了?

标签: c# mysql entity-framework ef-code-first entity-framework-core


【解决方案1】:

有不同的可能性需要考虑

方法一

制作附件表来存储表名和id

然后当你得到一些对象 Product 时,检查它是否有一个使用 ProdcutId 的附件和可以使用反射访问的表名

优点

  • 你摆脱了导致some toubles的GUID

  • 你有一个简单的表结构,只有IdRefrencedTableRefrencedId

缺点

访问附件列表将执行全表扫描(您可以使用索引将这种影响最小化)仍然需要与字符串 RefrencedTable 进行比较

方法二

在所有需要的表中定义一个Attachments 列表,这将为每个表创建一个外键

优点

  • 更容易从任何其他对象访问Attachments 列表

  • 仍然没有指导

缺点

可能是非常大的表,其中包含很多可为空值和索引

方法3

使用共享 GUID

优点

缺点

处理所有表必须唯一的 GUID 序列

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 2011-08-08
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多