简体   繁体   English

具有层次结构的EF Code First属性

[英]EF Code First property with hierarchy

While using Entity Framework Code First 6, I'm trying to replicate the following model: 在使用Entity Framework Code First 6时,我正在尝试复制以下模型:

模型设计

Class A is an abstract class, implemented by A1 and A2. 类A是由A1和A2实现的抽象类。 Additionally, class A exposes a navigation property, navigationPropertyB, to class B which is an abstract class implemented by B1 and B2. 此外,类A向类B公开了导航属性navigationPropertyB,该类B是由B1和B2实现的抽象类。

Class A objects can have one class B object and Bs can participate multiple times in class A instances. A类对象可以具有一个B类对象,并且B可以多次参与A类实例。

Currently for A I'm using Table per Hierarchy and for B Table per Concrete Type . 目前,对于A我正在使用每个层次结构的表 ,对于B 具体类型使用B

Class A hierarchy is mapped correctly and the following mapping is being used: 类A层次结构已正确映射,并且正在使用以下映射:

    modelBuilder.Entity<A>()
                .Map<A1>(m => m.Requires("AType").HasValue((int)AType.A1))
                .Map<A2>(m => m.Requires("AType").HasValue((int)AType.A2))

I understand it's a similar concept but I'm struggling to get a working mapping to model A's navigationPropertyB. 我理解这是一个相似的概念,但是我正在努力获取模型A的navigationPropertyB的有效映射。

Can anyone help? 有人可以帮忙吗?

Thank you! 谢谢!

You're trying to create a one-to-many relationship between A and B , since each B can potentially have a relationship with multiple A s. 您正在尝试在AB之间A一对多关系,因为每个B都可能与多个A关联。 A problem here is that since you're using Table per Concrete Type (TPC) inheritance for B 's hierarchy, you won't be able to create a single association between A and classes in the hierarchy of B . 这里的问题是,因为您正在为B的层次结构使用每个具体类型的表(TPC)继承,所以您将无法在AB的层次结构中的类之间创建单个关联。 Here's a quote from your linked article on TPC : 这是您在TPC上链接文章的引文:

...the SQL schema is not aware of the inheritance; ... SQL模式不知道继承; effectively, we've mapped two unrelated tables to a more expressive class structure.... I have to emphasize that there is no relationship between the database tables, except for the fact that they share some similar columns. 有效地,我们已经将两个不相关的表映射到一个更具表现力的类结构。...我必须强调,数据库表之间没有任何关系,除了它们共享一些相似的列。

In other words, with TPC, since the types do not share a table, it is possible to have duplicate key values across entities within B 's hierarchy! 换句话说,使用TPC,由于类型不共享表,因此有可能在B的层次结构中的各个实体之间具有重复的键值!

So if you want to create an association between A and B you'll need to either 因此,如果要在AB之间创建关联,则需要

  • Create a separate association with each concrete type in B 's hierarchy B层次结构中的每个具体类型创建一个单独的关联
  • Change the inheritance mapping to TPH or TPT 将继承映射更改为TPH或TPT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM