Reputation: 45242
I'm using Entity Framework with .NET 4.0 and SQL Server 2008.
I have two entities A
and B
, A
has many B
's (there's a
field on B
table, i.e. B
->many to one ->A
). When I try to delete a specific parent entity A
, the query fails
A is parent entity, B is children entity.
Here's the code I use for deletion of a particular A
entity:-
var obj = (from A in context.As where A.id=someValue select A).First();
context.As.DeleteObject(obj);
context.SaveChanges();
However it throws the famous exception
The DELETE statement conflicted with the REFERENCE constraint "FK_bs_as". The conflict occurred in database "myDb", table "dbo.bs", column 'a'.
The statement has been terminated.
Then I looked at the foreign key constraint using SQL Server Management Studio and edited FK as follows:
and tried to set FK to ON DELETE CASCADE
. However obviously there's still a problem with it.
I don't want to fetch every damn child entity (B
) of the parent entity (A
) and delete them individually. That's too expensive when compared to executing a single SQL query.
Upvotes: 0
Views: 2630
Reputation: 1
OnDelete
to Cascade
in EDMXmodel.edmx.sql
to re-create the databaseUpvotes: 0
Reputation: 83
Be sure that your entity model is in sync with the database model. Refresh your entity model every time you make changes to the database (update model from database), otherwise you can get unexpected exceptions.
Upvotes: 0
Reputation: 364349
What you need to do is:
The first step will ensure that cascade delete will work if your related entities are not loaded and second step will ensure that cascade delete delete will work if your related entities are loaded. Both steps are necessary.
Once you have this done you don't need to load related entities and delete them one by one.
Upvotes: 4