当数据库没有这个设置时如何级联删除?
How to delete on cascade with when the database has not this set?
我有一个 SQL 服务器数据库,其中有两个 table 具有 1:N 关系。在关系中我设置了删除时,什么都不做,因为通常我想在逻辑业务中控制它,我的意思是,在我的存储库中。
所以在我的存储库中,我得到了我需要从两个 table 中删除的行,理论上我得到了主 table 的所有 parent 行是 child table 行的 parents。所以我不会有任何问题。
但我知道当我做 saveChanges
时,EF 不能确保删除的顺序,所以有可能在删除所有 child 之前尝试删除 parent s,原来是这个问题。
所以我的问题是,是否有任何方法可以配置 dbContext
,两个实体的关系删除行而不会有这个问题?
我的代码是:
using(MyEntities myDbContext = new myEntities())
{
//Here I could configure myDbContext to perform a correct deleting?
//code to get the rows to delete
myDbContext.SaveChanges(); //here is the error.
}
谢谢。
该实体应包含与其相关的 entity/table 的导航 属性。假设 table a 是父 table,然后您将删除导航 属性 中指向子 table/table b 的所有记录。然后您将从 table a 中删除记录。然后调用 myDbContext.SaveChanges() ,EF 会为您处理删除内容的所有级联。
我有一个 SQL 服务器数据库,其中有两个 table 具有 1:N 关系。在关系中我设置了删除时,什么都不做,因为通常我想在逻辑业务中控制它,我的意思是,在我的存储库中。
所以在我的存储库中,我得到了我需要从两个 table 中删除的行,理论上我得到了主 table 的所有 parent 行是 child table 行的 parents。所以我不会有任何问题。
但我知道当我做 saveChanges
时,EF 不能确保删除的顺序,所以有可能在删除所有 child 之前尝试删除 parent s,原来是这个问题。
所以我的问题是,是否有任何方法可以配置 dbContext
,两个实体的关系删除行而不会有这个问题?
我的代码是:
using(MyEntities myDbContext = new myEntities())
{
//Here I could configure myDbContext to perform a correct deleting?
//code to get the rows to delete
myDbContext.SaveChanges(); //here is the error.
}
谢谢。
该实体应包含与其相关的 entity/table 的导航 属性。假设 table a 是父 table,然后您将删除导航 属性 中指向子 table/table b 的所有记录。然后您将从 table a 中删除记录。然后调用 myDbContext.SaveChanges() ,EF 会为您处理删除内容的所有级联。