Daniel Marín
Daniel Marín

Reputation: 1447

EF Code First: can i perform Delete Cascade without changing the Database?

I want to activate Delete Cascade in some relations of my entities, but I don't want to change the database. I wonder if there is a way to do this in Entity Framework.

I mean, it would be perfect if EF just generates automatically the SQL calls to remove all the related records when the parent is removed.

I was trying to add this to my SonEntityTypeConfiguration class:

public SonEntityTypeConfiguration()
    {
        HasRequired(e => e.Parent)
            .WithMany()
            .WillCascadeOnDelete(true);

        //(...)
    }

but I'm getting this error:

The model backing the 'AuditoriaUnitOfWork' context has changed since the database was created. Consider using Code First Migrations to update the database

So it seems to be still trying to change the database.

Is there any way to achieve this or I should give up and just ask my database manager to change it?

Upvotes: 1

Views: 69

Answers (2)

Kenneth Cochran
Kenneth Cochran

Reputation: 12104

WillCascadeOnDelete relies on cascading deletes at the database level. So it will require a schema change.

The reason cascading deletes are not implemented at the EF layer is because there are no guarantees that EF will even be used. There are numerous ways to access the database but it is the database's responsibility to ensure that referential integrity is maintained. It cannot rely on higher layers for this.

Upvotes: 1

Norman
Norman

Reputation: 3479

You have two options here: You can use WillCascadeOnDelete which requires a migration (* if you did not implement it in the first place) or you can delete any related objects on your own.

Upvotes: 0

Related Questions