Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Cascading Deletes & Lazy Loading

I am using the Northwind sample database. I have this code:

var db = new NorthwindEntities();
int id = 2; // Example
var delObject = (from o in db.Orders.Include("Order_Details")
                 where o.OrderID == id
                 select o).First();
db.Orders.DeleteObject(delObject);
db.SaveChanges();
  • I have an (1-to-many) association in Order - Order Details, with cascading deletes. (If I delete one Order, all Order_Details with the same OrderID will be deleted).

  • I have LazyLoading enabled.

If I delete the .Include("Order_Details") in the from clause, the cascade delete won't work.

Why does this happen? Isn't lazy initialization supposed to "include" the Order_Details for me, and eventually let me cascade delete?

like image 917
ColdFusion Avatar asked Jan 30 '12 15:01

ColdFusion


People also ask

Does Entity Framework cascade delete?

The EF Core in-memory database does not currently support cascade deletes in the database.

What is a cascading delete?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.

Is Cascade delete good practice?

On delete cascade is a particularly bad thing to use to clean data because it doesn't discriminate against the data you want the FK to stop the delete for and the data you are trying to completely purge.

Is Cascade delete default?

To prevent records from being accidentally deleted, cascade-delete is disabled by default.


3 Answers

The cascading deletes is defined in your EF model.

EF will therefore generate delete statements for data that it has loaded. EF will not go to the database to check what it should delete.

You can define cascading deletes (depending on your database) at the database level. In this case EF will delete the top node and the database will delete the related rows.

like image 115
Shiraz Bhaiji Avatar answered Oct 05 '22 20:10

Shiraz Bhaiji


Do you have the cascading delete defined in both the database and the entity configuration? I've seen where having it defined in only one and not the other can cause this problem.

like image 27
Jeff Siver Avatar answered Oct 05 '22 20:10

Jeff Siver


Cascade deletions in EF model deletes only those details which has been loaded in context. In case if you do use Include Order_Details are loaded during query along with Orders. If you enabled LazyLoading and not use Include then they are loaded on as needed basis, i.e. when you reference navigation properties. Thus if you don't care about details and agree that they will be silently deleted with master record you have to define cascade deletion both in EF model and DB schema.

like image 37
Vitaliy Kalinin Avatar answered Oct 05 '22 22:10

Vitaliy Kalinin