且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架,外键约束可能会导致循环或多个级联路径

更新时间:2023-02-03 07:58:19

无法级联删除到同一表一直是Sql Server的限制.只是谷歌的错误信息.基本上,如果要使用级联删除,则必须确保只有一个级联路径.

Not being able to handle multiple cascade paths and cascade delete to same table has been a limitation of Sql Server for a long time. Just Google the error message. Basically, if you want to use cascade delete then you'll have to make sure that there is only a single cascade path.

目前,您有两条来自分支"->"UsersBranchs"和分支->"Users"->"UsersBranchs"的路径.

At the moment you have two paths from Branchs -> UsersBranchs and Branchs -> Users -> UsersBranchs.

默认情况下,EF会设置级联删除,但是可以通过删除DbContext中的约定来停止它.

EF by default sets cascade delete but it may be stopped by removing the conventions in your DbContext.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Manually set cascade delete behaviour
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

    base.OnModelCreating(modelBuilder);
}

然后,您必须在要级联删除的任何关系上设置WillCascadeOnDelete(true).请参阅实体框架文档.

Then you'll have to set WillCascadeOnDelete(true) on any relationships where you want cascade delete. See the Entity Framework documentation.

除此之外,您的模型似乎有些奇怪.您看起来好像试图建立一个多对多链接/联接表UsersBranchs,但是您在Branchs上也只有一个User并没有任何意义.在这种情况下,您甚至需要UsersBranchs表吗?您是不是要在您的分支机构上拥有一组用户,即导航属性而不是外键,从而提供了一对多的关系分支机构->用户?

Other than that your model seems a bit strange. You look like you're trying to make a many-to-many link/join table, UsersBranchs, but you also have a single User on the Branchs which doesn't really make sense. Do you even need the UsersBranchs table in that case? Did you mean to have a collection of Users on your Branchs, i.e. a navigation property rather than a foreign key, which gives a one-to-many relationship Branchs -> Users?

顺便说一句,我真的不喜欢对单个实体使用复数.

As an aside I really dislike using plurals for single entities.