5

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?

Yuck
  • 49,664
  • 13
  • 105
  • 135
ColdFusion
  • 93
  • 8

3 Answers3

5

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.

Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252
1

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.

Jeff Siver
  • 7,434
  • 30
  • 32
1

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.

Vitaliy Kalinin
  • 1,791
  • 12
  • 20