Today i came across some very odd behaviour using Linq to SQL.
I was trying to retrieve a record from the database to update one column then save the change to the database. The problem was happening when i tried to save the change. I was getting foreign constraint errors on related records that didn’t even exist!

Here is the DB structure:
T1 (id, value)
T2 (id,, values)
T3 (id,, values)

T1 existed but T2 and T3 didn’t. The foreign key constraint error i recieved was between T2 and T3 but how can that be when i didn’t create any records and they don’t exist?!

Here is the code i initially used:

DataContext Dal = new DataContext();
T1 table1 =  (from t in DC.T1

    where == pID

    select t).SingleOrDefault();
table1.value = pNewValue;


When i inspected the object VS showed that T1 had at least 1 T2 object and when i inspected T2 it had at least one T3 object.

The fix for this was to change the Linq select statement but i don’t for the life of me know why this made a difference. Here is the fixed version:

DataContext Dal = new DataContext();

T1 table1 =  Dal.T1.Where(a => == pID).SingleOrDefault();

table1.value = pNewValue;


Has anyone else ever experienced this?

You may also like

New Products Launch and Redesign of Simply Energy website

The team has been busy with the re-design of the Simply Energy (SE) website to accommodate the launch of a new range of electricity and gas offers available to the public on the 25th of May 2009. The redesign was initiated by the SE Marketing team and the campaign is aimed at driving more visitors to the site to ultimately result in more supply contracts for SE.

Keep Reading

ASP.NET Button – Prevent Double Clicks

Virtually every developer has met the situation when a page postback takes quite some time and the user must be prevented from submitting the form twice. The task sounds easy, doesn’t it? Unfortunately there is no easy and straighforward way in ASP.NET to accomplish this.

Keep Reading

Newsletter sign up

Every couple of months we send out an update on what's been happening around our office and the web. Sign up and see what you think. And of course, we never spam.