且构网

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

级联删除问题?

更新时间:2023-02-05 12:14:01

我也遇到了这个问题,不得不关闭级联删除,默认情况下代码首先打开。 在OnModelCreating的模型类中,你需要添加一些代码来关闭它:

 modelBuilder.Entity< 实体>()
.HasMany(u  =>  u.Collection)
.WithRequired(a  =>  a.Entity)
.WillCascadeOnDelete( false );

 通过流畅的API添加此行后,它全部工作了对我来说。 不幸的是,使用流利的API是我认为可以执行此操作的唯一方式。


 


Dane


I'm using code-first, data annotations, and trying to avoid the fluent api.

<rant>I'm getting really frustrated trying to accomplish simple things...</rant>

I have a object/table, StockOrder that has a reference/fk to a Location object/table

I have another table, Organization, that also has a reference/fk to Location.

I am getting the error, when creating the database

Introducing FOREIGN KEY constraint 'StockOrder_OrderedFromLocation' on table 'StockOrders' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint.

What do I need to do here? I am *assuming* that deletion of StockOrder will cause the "Location" to be deleted, and this causes conflect if "Organization" gets deleted? I don't want any cascade, so how do I turn this off? If I have to use the Fluent API, can someone point me to the sample code? Otherwise, how do I decorate this with data annotation.

Help would be much appreciated... I've spent 2 days and I still don't have a simple, realistic database setup yet.

I ran into this issue too and had to turn off cascading deletes, which code first has on by default.  In your model class in the OnModelCreating you willl need to add some code to turn this off:

modelBuilder.Entity<Entity>()
.HasMany(u => u.Collection)
.WithRequired(a => a.Entity)
.WillCascadeOnDelete(false);

 After adding this line through the fluent API it all worked for me.  Unfortunately using the fluent API is the only way I believe that is available to do this.

 

Dane