【问题标题】:Entity Framework foreign key to multiple tables/entities多个表/实体的实体框架外键
【发布时间】:2017-01-09 19:48:27
【问题描述】:

我需要使用实体框架在多个数据表上实现实体-属性-值功能。假设我有一个属性值 EF 类,如下所示:

public class EntityAttributeValue
{
    // Not important to my question.
    public virtual Entity ParentEntity { get; set; }
    public virtual EntityAttribute ParentEntityAttribute { get; set; }

    // Field in question.
    public Guid ParentSurrogateKey { get; set; }

    public string Value { get; set; }

    ...
}

然后我有多个实体具有与之关联的补充 EAV 值:

public class Entity1
{
    // Key.  EntityAttributeBalue.ParentSurrogateKey maps to this.
    [Key]
    public Guid SurrogateKey { get; set; }

    // Standard properties.
    public string Property1 { get; set; }
    public string Property2 { get; set; }

    // Collection of EAV values associated with this entity/table.
    [ForeignKey("ParentSurrogateKey")]
    public virtual IList<EntityAttributeValue> EntityAttributeValues { get; set; }
}

public class Entity2
{
    // Key.  EntityAttributeBalue.ParentSurrogateKey maps to this.
    [Key]
    public Guid SurrogateKey { get; set; }

    // Standard properties.
    public string OtherProperty1 { get; set; }
    public string OtherProperty2 { get; set; }

    // Collection of EAV values associated with this entity/table.
    [ForeignKey("ParentSurrogateKey")]
    public virtual IList<EntityAttributeValue> EntityAttributeValues { get; set; }
}

我的问题是 Entity1 和 Entity2 都有与之关联的 EntityAttributeValue 对象。代码优先迁移尝试在 ParentSurrogateKey 上创建一个从 EntityAttributeValue 到 Entity1 的外键和另一个返回到 Entity2 的外键。任何单个给定 EntityAttributeValue 的代理键仅与一个 Entity1 或一个 Entity2(或扩展为一个 EntityN...)相关联,而不是两者/全部。

我在这里有一个多对多的关系,但一侧不仅映射到多行,而且映射到共享 GUID 列上的多个实体/表。

我应该如何处理这个问题?我是否应该将 EntityAttributeValue 外键从自动迁移中删除回 Entity1 和 Entity2(这将是一个长期的痛苦)?我是否应该手动检索给定 EAV 实体的 EntityAttributeValues 列表,而不是依靠 EF 为我完成?

【问题讨论】:

  • 我认为这是一个基本的 EF 新手问题。如果您实际上将其设置为多对多,则自动创建的连接表将处理这种情况。我以为我已经尝试过了,但显然没有。如果这成功了,我会回答我自己的问题。

标签: c# entity-framework foreign-key-relationship


【解决方案1】:

嗯,答案很明显很简单。我需要使用 FluentAPI 定义多对多关系。在 OnModelCreating 中,我刚刚添加了:

            modelBuilder.Entity<Entity1>()
                .HasMany(m => m.EntityAttributeValues)
                .WithMany();

            modelBuilder.Entity<Entity2>()
                .HasMany(m => m.EntityAttributeValues)
                .WithMany();

我以为我已经尝试过了,但我想我没有。因为多对多关系为每个实体创建了一个中间表,并且外键在该中间表上(当给定的 EntityAttributeValue 应用于给定实体时,中间表中只有一行),所以没有外键问题.

【讨论】:

  • 我感到困惑的一个原因是,给定的 EntityAttributeValues 对象总是只有一个 EntityN 对象。但是,由于不同的 EntityAttributeValues 实例可以映射到不同类型(类)的 EntityN 对象,因此将关系表示为多对多是避免问题的权宜之计。这种策略有可能被视为“笨拙”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多