Interesting LinqToSql behaviour

Posted by Ben Robinson on Stack Overflow See other posts from Stack Overflow or by Ben Robinson
Published on 2010-06-01T16:22:29Z Indexed on 2010/06/01 16:23 UTC
Read the original article Hit count: 222

Filed under:
|
|
|

We have a database table that stores the location of some wave files plus related meta data. There is a foreign key (employeeid) on the table that links to an employee table. However not all wav files relate to an employee, for these records employeeid is null. We are using LinqToSQl to access the database, the query to pull out all non employee related wav file records is as follows:

var results = from Wavs in db.WaveFiles
              where Wavs.employeeid == null;

Except this returns no records, despite the fact that there are records where employeeid is null. On profiling sql server i discovered the reason no records are returned is because LinqToSQl is turning it into SQL that looks very much like:

SELECT Field1, Field2 //etc
FROM WaveFiles
WHERE 1=0

Obviously this returns no rows. However if I go into the DBML designer and remove the association and save. All of a sudden the exact same LINQ query turns into

SELECT Field1, Field2 //etc
FROM WaveFiles
WHERE EmployeeID IS NULL

I.e. if there is an association then LinqToSql assumes that all records have a value for the foreign key (even though it is nullable and the property appears as a nullable int on the WaveFile entity) and as such deliverately constructs a where clause that will return no records.

Does anyone know if there is a way to keep the association in LinqToSQL but stop this behaviour. A workaround i can think of quickly is to have a calculated field called IsSystemFile and set it to 1 if employeeid is null and 0 otherwise. However this seems like a bit of a hack to work around strange behaviour of LinqToSQl and i would rather do something in the DBML file or define something on the foreign key constraint that will prevent this behaviour.

© Stack Overflow or respective owner

Related posts about c#

Related posts about sql