Linq to SQL Null Value Handling

Here is what SQLMetal generates when you have a column in your database that allows nulls:

private System.Nullable<int> _DiscountTypeID;

This means that when you have a null value in the database, the value that is returned by the Linq to SQL engine is a .net null, not a crazy datetime.minvalue or some other such nonsense. Nice and intuitive.

For a nested entity, you get this:

private EntityRef<DiscountTypes> _DiscountTypes;

This also handles null referenced values as nulls. So far so good.

But what happens when a column in your database does not allow nulls when you generate the dbml file but allows it at run time? This could be the difference between your dev and stage databases. As with the missing tables from a my previous post, the code will compile but you'll get the following exception:

"The null value cannot be assigned to a member with type System.DateTime which is a non-nullable value type."

So with Linq to SQL, we've really just pushed the inherent problems with keeping databases in sync to another level. You get compile time checking against your schema, not against the actual database. This is not a terrible thing in my opinion, its just a gotcha that you need to be aware of and handle the possibilities in your code.

JJ

3 Comments

Comments have been disabled for this content.