LINQ to SQL Tips 4: Use DeleteOnNull if you want to delete object with null FK

I often get a question along the following lines:

If I remove one of the OderDetails from Order.OrderDetails collection, I see that the reference OrderDetail.Order is set to null but this just orphans the OrderDetail; it is not deleted. How can I change that?

Here is how:

This is not exposed in the designer so you will need to change the generated code (ouch!). In the Association attribute, set the DeleteOnNull property to true as follows:

Once this is set, either of the following operations

ord.Order_Details.Remove(od); // ord is Order; od is OrderDetail

od.Order = null;

will result in the following being inferred:

// db is an instance of the strongly typed DataContext

Please note that this is not the same as cascade delete. Cascade delete is what you specify on your foreign key in the database - for all apps. LINQ to SQL deliberately does not take over this database role. What it does is provide a shorthand notation to say that a particular type is the target of cascade delete constraint in the database (not the source) and hence can be cleaned up when the nullable foreign key is set to null. LINQ to SQL does not by itself provide cascade delete behavior.

Comments (5)

  1. WPF Panel3D now supports transparency [Via: Josh Smith ] Code Camps CodeStock in Knoxville, TN on August…

  2. Hot Topics says:

    Dinesh Kularni , who was formerly on the LINQ to SQL team and is now on the Silverlight team, has been

  3. Dinesh Kularni a publié depuis novembre 5 astuces sur LINQ To SQL : LINQ to SQL Tips 1: how to map an

  4. I found a series of LINQ to SQL tips over at Dinesh’s Cyberstation . LINQ to SQL Tips 1: how to map an enum LINQ to SQL Tips 2: how to use common base class for all entities LINQ to SQL Tips 3: Deferred (lazy) or eager loading of related objects with

  5. Dave Brace says:

    My first project at Catalyst just wrapped up this past week, and it involved creating an order fulfillment

Skip to main content