实体框架 - 使用外键插入
如果某处对此有明确的答案,我们深表歉意。但我无法插入到一个简单的表中,因为它包含外键。
任务表
我尝试像这样插入:
任务 t = new Task();
t.Id = 1234;
t.Title = “foo”;
t.Status = db.Status.ToList().First();
但出现 updateException 错误: <我> 正在从 AssociationSet“FK_Task_Status”添加或删除关系。通过基数约束,还必须添加或删除相应的“任务”。
如何插入此表?
干杯
...
发现我的问题....
我的架构错误。当我创建外键时,我将其指向了错误的字段。查看了 SQL 探查器,看到了这个:
<块引用>选择 1 作为[C1], [范围 1].[Id] AS [Id], [范围 1].[描述] AS [描述], [范围 2].[Id] AS [Id1] FROM [dbo].[状态] AS [范围 1] 左外连接 [dbo].[任务] AS [扩展 2] ON [扩展 1].[Id] = [扩展 2].[Id]
应该是这样的(加入 statusId 而不是 id):
<块引用>选择 1 作为[C1], [范围 1].[Id] AS [Id], [范围 1].[描述] AS [描述], [范围 2].[Id] AS [Id1] FROM [dbo].[状态] AS [范围 1] LEFT OUTER JOIN [dbo].[Task] AS [Extent2] ON [Extent1].[Id] = [Extent2].[StatusId]
我真傻;)
Apologies if there is clear answer for this somewhere. But I can't insert into a simple table due to it containing a foreign key.
Task Table
Into which I try to insert like so:
Task t = new Task();
t.Id = 1234;
t.Title = "foo";
t.Status = db.Status.ToList().First();
But get an updateException error:
A relationship is being added or deleted from an AssociationSet 'FK_Task_Status'. With cardinality constraints, a corresponding 'Task' must also be added or deleted.
How can I insert into this table?
Cheers
....
Found my issue....
My schema was wrong. When I created my foreign key I pointed it to the wrong field. Had a look in SQL profiler, saw this:
SELECT
1 AS [C1],
[Extent1].[Id] AS [Id],
[Extent1].[Descr] AS [Descr],
[Extent2].[Id] AS [Id1]
FROM [dbo].[Status] AS [Extent1]
LEFT OUTER JOIN [dbo].[Task] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Id]
Which should be this (joining on statusId not id):
SELECT
1 AS [C1],
[Extent1].[Id] AS [Id],
[Extent1].[Descr] AS [Descr],
[Extent2].[Id] AS [Id1]
FROM [dbo].[Status] AS [Extent1]
LEFT OUTER JOIN [dbo].[Task] AS [Extent2] ON [Extent1].[Id] = [Extent2].[StatusId]
Silly me ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在.net Framework 4.0中,您可以使用这种简单的方法:
参考:http://blogs.msdn.com/b/adonet/archive/2009/11/06/foreign-key-relationships-in-the-entity-framework。 ASPX
in .net framework 4.0 u can use this simple way:
reference: http://blogs.msdn.com/b/adonet/archive/2009/11/06/foreign-key-relationships-in-the-entity-framework.aspx
使用“Entity Framework 1.0”(迄今为止最新的版本),您有正确的想法 - 从数据库获取状态以在任务上设置。您确定您确实使用上面使用的语法获得了 Status 实体吗?
单步执行代码以确保任务实体上的引用被设置为实际的具体化状态实体。
Using "Entity Framework 1.0" (the version that was, until today, the most current) you have the right idea- get the Status from the database to set on the Task. Are you sure you're actually getting a Status entity with the syntax you're using above?
Step through your code to make sure the reference on the Task entity is being set to an actual materialized Status entity.
你可以尝试
希望这会起作用
you can try
hope this will work