Discarding new entity objects in LINQ to SQL beta 1

An unusual bug in .NET Framework 3.5 beta 1 that relates to creating a new entity object in LINQ to SQL has been getting in my way.

Bug description

When you create a new entity object it is not automatically added to the database unless you either attach it to the table or create an association to another existing entity.

The problem arises when you decide to discard the new object instead of persisting it. Setting the property of the association(s) to null should achieve this and the LINQ to SQL designer code shows that it removes the new object from the association.

When SubmitChanges is called it is apparent that the new object has not been discarded but is in fact attempting to persist to the database.


  1. Create a new C# Console project
  2. Add a new a LINQ to SQL file and name it Northwind
  3. Use Server Explorer to drag Orders and Customers tables from a Northwind database connection
  4. Paste the following code snippet into the static main method
  5. Run the program
  6. Examine the Orders table and notice a new a record consisting of null fields
NorthwindDataContext dc = new NorthwindDataContext();
Customer alfredCustomer = dc.Customers.Single(c => c.CustomerID == "ALFKI");
Order newOrder = new Order();
newOrder.Customer = alfredCustomer;
newOrder.Customer = null;


It would appear there is at least a temporary workaround which is to force the association that was modified to reload. You can do this by calling the associations Load method after the entity has been de-associated but before SubmitChanges.

In our reproduction this would therefore be:

newOrder.Customer = null;

Calling Load does not disrupt other still-valid associations that have not yet persisted.

Curiously accessing the Count property of the association also causes the problem to disappear because the EntitySet<T> class that is responsible for representing these one-to-many associations calls Load every time you access Count. This is a potential performance hit as accessing a Count` property is considered to be a fast operation that does not go off and rebuild collections.

Here’s hoping that Microsoft fix those two bugs before release and ideally before beta 2.


2 responses

  1. Avatar for Matt Warren

    Fortunately, since I fixed those myself, I can honestly say they are fixed in Beta 2.

    Matt Warren June 24, 2007
  2. Avatar for Damien Guard

    Great to hear Matt.

    Looking forward to beta 2 :)

    Damien Guard June 24, 2007