实体框架多个表/实体的外键

时间:2017-01-09 19:48:28

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

我需要使用Entity Framework在多个数据表上实现Entity-Attribute-Value功能。假设我有一个属性值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对象。代码优先迁移尝试从EntityAttributeValue创建一个外键返回到Entity1,另一个外键返回到ParentSurrogateKey上的Entity2。任何单个给定EntityAttributeValue的代理键仅与一个Entity1或一个Entity2相关联(或者,扩展,一个EntityN ...),而不是两者/全部。

我在这里有很多关系,但是一方不仅映射到多行,而且通过共享GUID列映射多个实体/表。

我该如何接近这个?我是否应该从自动迁移中删除EntityAttributeValue外键到Entity1和Entity2(这将是一个长期的痛苦)?我应该手动检索给定EAV实体的EntityAttributeValues列表,而不是依靠EF来为我做这个吗?

1 个答案:

答案 0 :(得分:1)

嗯,答案结果显而易见。我需要与FluentAPI定义多对多关系。在OnModelCreating中,我刚刚添加了:

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

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

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