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.

Reproduction

  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;
dc.SubmitChanges();

Workaround

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;
alfredCustomer.Orders.Load();
dc.SubmitChanges();

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_ 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.

[)amien

2 responses

  1. Gravatar for Matt Warren

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

    Matt Warren – June 24th, 2007
  2. Gravatar for Damien Guard

    Great to hear Matt. Looking forward to beta 2 :)

    Damien Guard June 24th, 2007

Respond to this