EntityFramework 的文档指出以下行为是可能的:
如果依赖实体上的外键可以为空,Code First 不会在关系上设置级联删除,并且当主体被删除时,外键将设置为空。
(来自http://msdn.microsoft.com/en-us/jj591620)
但是,我无法实现这种行为。
我有以下使用代码优先定义的实体:
public class TestMaster
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<TestChild> Children { get; set; }
}
public class TestChild
{
public int Id { get; set; }
public string Name { get; set; }
public virtual TestMaster Master { get; set; }
public int? MasterId { get; set; }
}
这是 Fluent API 映射配置:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TestMaster>()
.HasMany(e => e.Children)
.WithOptional(p => p.Master).WillCascadeOnDelete(false);
modelBuilder.Entity<TestChild>()
.HasOptional(e => e.Master)
.WithMany(e => e.Children)
.HasForeignKey(e => e.MasterId).WillCascadeOnDelete(false);
}
外键可以为空,导航属性映射为可选,所以我希望级联删除按照 MSDN 的描述工作 - 即取消所有子项的 MasterID,然后删除 Master 对象。
但是当我实际尝试删除时,我收到了 FK 违规错误:
using (var dbContext = new TestContext())
{
var master = dbContext.Set<TestMaster>().Find(1);
dbContext.Set<TestMaster>().Remove(master);
dbContext.SaveChanges();
}
在 SaveChanges() 上,它抛出以下内容:
System.Data.Entity.Infrastructure.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
----> System.Data.UpdateException : An error occurred while updating the entries. See the inner exception for details.
----> System.Data.SqlClient.SqlException : The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.TestChilds_dbo.TestMasters_MasterId". The conflict occurred in database "SCM_Test", table "dbo.TestChilds", column 'MasterId'.
The statement has been terminated.
我做错了什么还是我误解了 MSDN 所说的内容?