我首先使用 EF 代码,然后使用 EF 4.X DbContext Fluent Generator T4 生成我的代码,所以现在我有 2 个 poco 实体(我将列表更改BindingList<T>为在 winForms 中使用绑定):
public partial class Parent
{
    public Parent()
    {
        this.Childs = new BindingList<Childs>();
    }
    int _ParentId;
    public int ParentId { get; set; }
    BindingList<Child> _Childs;
    public virtual BindingList<Child> Childs { get; set; }
}
public partial class Child
{
    int _ChildId;
    public int ChildId { get; set; }
    int _ParentId;
    public int ParentId { get; set; }
    Parent_Parent;
    public virtual Parent Parent { get; set; }
}
而且我的映射文件是:
    public Parent_Mapping()
    {                   
        this.HasKey(t => t.ParentId);       
        this.ToTable("Parent");
        this.Property(t => t.ParentId).HasColumnName("ParentId");
    }
    public Child_Mapping()
    {                   
        this.HasKey(t => t.ChildId);        
        this.ToTable("Child");
        this.Property(t => t.ChildId).HasColumnName("ChildId");
        this.Property(t => t.ParentId).HasColumnName("ParentId").IsRequired();
        this.HasRequired(t => t.Parent)
            .WithMany(t => t.Childs)
            .HasForeignKey(t=>t.ParentId)
            .WillCascadeOnDelete(true);
    }
在我的 DbContext 我有这些代码:
public partial class MyContext : DBContext
{ 
    static MyContext()
    { 
       Database.SetInitializer<MyContext>(null);
    } 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
        modelBuilder.Configurations.Add(new Parent_Mapping());
        modelBuilder.Configurations.Add(new Child_Mapping());
    }
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Childs { get; set; }
}
所以我有一个启用级联删除的一对多关系。
但是当我想删除一个父实体时,我收到了这个错误:
{
 "Cannot insert the value NULL into column 'ParentId', table 'MyDB.dbo.Child';
  column does not allow nulls. UPDATE fails.\r\nThe statement has been terminated."
}
当我使用 EF Profiler 进行监控时,我看到 EF 想要更新 Child 表以将 ParentId 设置为 Null,而不是删除父实体!:
update [dbo].[Child]
set    
   [ParentId] = null,
where  ([ChildId] = 2 /* @1 */)
我的错误在哪里?