【发布时间】:2013-12-17 13:48:47
【问题描述】:
假设我有这种情况:
Table Bar
Id int not null
Name string not null
和
Table Foo
Id int not nul
BarId int foreign key (Bar) references Id
当我尝试删除在 Foo 中有引用的 Bar 时,为什么 EF 尝试更新 Foo 将 BarId 设置为 NULL?
当有人尝试将 NULL 设置为 Bar 时,我对我的属性进行了验证,当 EF 尝试更新 Foo 时我收到此错误。
如果我尝试删除执行“从 foo 中删除 id = 1”之类的查询,我会得到:
The DELETE statement conflicted with the REFERENCE constraint "FooFK".
The conflict occurred in database "teste", table "dbo.Bar", column 'BarId'.
我想在使用 EF 时收到此错误。有什么办法可以做到这一点? 我正在使用 EF 4.3。
这是我的地图:
modelBuilder.Entity<Bar>().HasRequired(x => x.Foo).WithMany().Map(x => x.MapKey("FooId")).WillCascadeOnDelete(false);
【问题讨论】:
-
由于约束,它尝试将 BarId 设置为 null。您没有级联删除,外键列需要一个值或空值。你能发布你的约束吗?
-
但是我的专栏不接受 NULL。
-
约束条件:ALTER TABLE [dbo].[Cargo] WITH CHECK ADD CONSTRAINT [CargoRaiz_Instituicao] FOREIGN KEY([Instituicao_Id]) REFERENCES [dbo].[Instituicao] ([Id])
标签: c# sql-server-2008 entity-framework entity-framework-4