链接表 - 代码优先 - 实体框架 - 表映射
我之前在这个论坛上问过一个相关的问题。这个问题概述了我所采取的步骤、我尝试过的不同事情以及我遇到的错误。它可能对某人有帮助。
考虑到涉及链接表的结构的映射,在我看来,代码优先、链接表和 TPH 存在一个怪癖,或者可能只是缺乏透明度。
我创建了一个带有 [Table("")] 属性的派生类,以将对象映射到以下类型的表结构:
(Case 1) Employees -> Attributes -> AttributeTypes
(Case 2) Employees -> EmployeeAttributeLink -> Attributes -> AttributeTypes
在前一种情况下,我实现了 TPH 查询和保存所需的结果。 (我使用数据注释属性和 Fluent api 将派生类映射到正确的鉴别器 id 列)。
但是,在第二种情况下我得到了这个错误: '实体类型 A 和 B 不能共享表 B,因为它们不在同一类型层次结构中 [或者] 它们之间没有有效的一对一外键关系和匹配的主键。需要有一个 1-1 对应关系”
当我查看它试图将类型映射到的表的名称时,我发现它很困惑。然而,我无法弄清楚我做错了什么,因为我在继承类之上使用了正确的表映射属性(我没有定义可能来自鉴别器的所有子类型 - 这有关系吗?)。
我引入了一些 FK 属性,试图解决错误消息中 [OR] 的第二部分。这导致我遇到了新问题,即无法确定委托人/受抚养人...然后我尝试使用[InverseProperty]属性...然后我开始抓狂。
现在,回滚并删除属性,我决定不依赖 [Table("")] 属性并使用 Fluent api 将类型映射到表。这似乎有效。
我的问题是:为什么 [Table("") ] 属性的行为和 Fluent API 上的 ToTable 函数的行为不同?我本以为它们是可以互换的
谢谢
I asked a related question previously on this forum. This question outlines the steps I have taken, different things I have tried and errors I have encountered. It might help someone.
Considering a mapping to a structure that involves a link table, it seems to me there is a quirk with Code First, Link Tables and TPH or perhaps just a lack of transparency.
I created a derived class with a [Table("")] attribute to map objects to the following sort of table structures:
(Case 1) Employees -> Attributes -> AttributeTypes
(Case 2) Employees -> EmployeeAttributeLink -> Attributes -> AttributeTypes
In the former case i achieved the results i wanted for TPH querying and saving. (I used data annotation attributes along with fluent api to map the derived classes to the correct discriminator id column).
However, in the second case I got this error:
'The entity types A and B cannot share table B because they are not in the same type hierarchy [OR] do not have a valid one to one foreign key relationship with matching primary keys between them. Need to have a 1-1 correspondence'
When I looked at the names of the tables that it was trying to map types to I could see it was confused. However I could not figure out what I was doing wrong as I had used the correct table mapping attribute above the inheriting classes (I didn't define all the sub types that could come from the discriminator - does that matter?).
I introduced some FK attributes trying to address the second part of the [OR] in the error message. This led me to new problems i.e. unable to determine principal/dependant... Then I tried to use the [InverseProperty] attributes... And then I started pulling my hair out.
Now, rolling back and removing the attributes, I decided not to rely on [Table("")] attribute and map the type to the table using the fluent api. This seems to work.
My question is: Why is it that the behaviour of the [Table("") ] attribute and the ToTable function on the fluent API behave differently? I would have thought they are interchangeable
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论