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.
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.
SubmitChanges is called it is apparent that the new object has not been discarded but is in fact attempting to persist to the database.
- Create a new C# Console project
- Add a new a LINQ to SQL file and name it Northwind
- Use Server Explorer to drag Orders and Customers tables from a Northwind database connection
- Paste the following code snippet into the static main method
- Run the program
- 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();
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();
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.