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
db.Order_Details.DeleteOnSubmit(od);

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.

Published 11 May 08 11:05 by Dinesh.Kulkarni

Comments

# Christopher Steen said on May 12, 2008 3:42 AM:

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

# Hot Topics said on May 19, 2008 3:35 PM:

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

# Matthieu MEZIL said on May 20, 2008 4:24 AM:

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

# LaptopHeaven: blogging that bytes said on July 7, 2008 9:05 AM:

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

# Dave Brace said on October 1, 2008 5:01 PM:

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

New Comments to this post are disabled

About Dinesh.Kulkarni

I am a program manager in the Visual C# Product Unit of Microsoft. I am currently working on the LINQ project with specific responsibility for DLinq. Previously, I have been in a PM in SQL Server working on ObjectSpaces and DataSet. In pre-MS life, I have worked for companies ranging from startup to IBM on a wide range of software projects. Before I started working, I did M.S.E.E. and Ph.D. (CSE) from the University of Notre Dame and B.Tech. E.E. from IIT Bombay, India.
Page view tracker