如何使用 Entity Framework 4.1 Code First 强制数据库中的一对多关系采用一对一关系
我尝试首先在架构无法更改的应用程序中将 EF1 更改为 EF4.1 代码,因为它用于 SQL Server 复制。该模式非常糟糕,并且在许多地方完全从前到后地描述了关系。
我想要做的是在两个类之间创建一对一的关系,但数据库模式错误地将数据维护为一对多。
public class ClassA
{
public ClassB
{
get;
set;
}
}
不幸的是,数据库中的表 ClassB 引用了 ClassAId,而不是引用了具有 ClassBId 的 ClassA,如下所示:
CREATE TABLE [dbo].[ClassA]
[Id] [bigint] IDENTITY
CREATE TABLE [dbo].[ClassB]
[Id] [bigint] IDENTITY
[ClassAId] [bigint]
如何设置从 EntityTypeConfiguration 继承的映射文件以强制建立此关系。
public class ClassAMapping : EntityTypeConfiguration<ClassA>
{
public ClassA()
{
HasKey(f => f.Id);
// what happens here to force a one to one????
}
}
I am trying to change EF1 for EF4.1 code first in an application where the schema cannot be changed because it is used in SQL Server Replication. The schema is dreadfully poor and in many places describes relationships completely back to front.
What I am trying to do is create a one to one relationship between two classes, but the database schema erroneously maintains the data as a one to many.
public class ClassA
{
public ClassB
{
get;
set;
}
}
Unfortunately the table ClassB in the database has reference to ClassAId rather than ClassA having a ClassBId as shown here:
CREATE TABLE [dbo].[ClassA]
[Id] [bigint] IDENTITY
CREATE TABLE [dbo].[ClassB]
[Id] [bigint] IDENTITY
[ClassAId] [bigint]
How to I set up my mapping file that inherits from EntityTypeConfiguration to force this relationship.
public class ClassAMapping : EntityTypeConfiguration<ClassA>
{
public ClassA()
{
HasKey(f => f.Id);
// what happens here to force a one to one????
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢 Jakub Konecki 提供了该文章的链接,它实际上并未包含我正在寻找的答案,但是它确实链接到我找到答案的系列中的早期帖子。
强制这种一对一关联的方法如下:
此映射读取为:
请注意,此解决方案是单向的,并且不允许以下操作:
如果需要双向关联,请查看 找到的链接进一步详细说明。
Jakub 链接的文章是 系列文章 如果您想理清与 EF4.1 的关联,这是一本很好的读物。
Thanks to Jakub Konecki for the link to the article, it did not actually contain the answer I was looking for, but it did link to an earlier post in the series where I found the answer.
The way to force this one to one association is as follows:
This mapping reads as:
Please note that this solution is uni-directional and will not allow the following:
If a bi-directional association is required check out the link that was found which elaborates further.
The article linked by Jakub is part of a series of posts which are a good read if you are trying to sort out your EF4.1 associations.
看一下这里:
http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part- 3-one-to-one-foreign-key-associations.aspx
这是一篇针对 CTP5 的文章,但我认为您将能够将流畅的 API 调用“翻译”为 RTm 版本。
Take a look here:
http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key-associations.aspx
It's an article for CTP5, but I think you will be able to 'translate' fluent API calls to RTm version.