Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 我首先在EF代码中的一对多关系中得到级联删除错误_Entity Framework_Ef Code First_Poco_Cascading Deletes - Fatal编程技术网

Entity framework 我首先在EF代码中的一对多关系中得到级联删除错误

Entity framework 我首先在EF代码中的一对多关系中得到级联删除错误,entity-framework,ef-code-first,poco,cascading-deletes,Entity Framework,Ef Code First,Poco,Cascading Deletes,我首先使用EF代码,并使用EF 4.X DbContext Fluent Generator T4生成代码,因此现在我有2个poco实体(我将列表更改为BindingList以在winForms中使用绑定): 在我的数据库上下文中,我有以下代码: public partial class MyContext : DBContext { static MyContext() { Database.SetInitializer<MyContext>(nu

我首先使用EF代码,并使用EF 4.X DbContext Fluent Generator T4生成代码,因此现在我有2个poco实体(我将列表更改为
BindingList
以在winForms中使用绑定):

在我的数据库上下文中,我有以下代码:

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; }
}
当我使用EF Profiler进行监视时,我看到EF希望更新子表以将ParentId设置为Null,而不是删除父实体!:

update [dbo].[Child]
set    
   [ParentId] = null,
where  ([ChildId] = 2 /* @1 */)

我的错在哪里?

我想原因是你把孩子和你的父母放在一起了。在这种情况下,还必须删除子项。若您只删除父EF,那个么它只会将关系设置为null。EF不会进行级联删除。级联删除仅在数据库中使用,并且仅在未加载子项时使用。如果已加载子实体,则会在删除父实体之前执行更新,并且会发生此异常

如果您希望加载的实体也具有类似于级联删除的行为,则必须使用名为的内容(您的子实体将具有由其id和父id组成的主键)

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."
}
update [dbo].[Child]
set    
   [ParentId] = null,
where  ([ChildId] = 2 /* @1 */)