Data Access in C#

I know, I know. It’s been far too long between posts. I’d like to claim that this is down the me being really busy crafting a superb, enterprise-scale initiative that will revolutionise the computer world, but it’s just that I’ve been way too lazy.
Anyway. More posts from now on. Promise.
Today, I was IMing with my good chum Justin (or Mostyn as he prefers to be called for reasons that escape me) about data access in .NET:
Mostyn: I walked into a trap yesturday when using Null columns in SQL. .Net can’t retrieve the value if it is set to null. Workaround seems to be to use things like Int32.MinValue as a psuedo null integer etc. I had to creat safe methods that test for null when retriving and test the .Net for psuedo null values before posting to SQL.
I pointed out that, in C# at least, you can use the (? 🙂 operator to get around the problem.
Rob: Something like this:
this.mExpires = (dr.IsDBNull(20) ? DateTime.MinValue : dr.GetDateTime(20));
It turned out that Justin, notwithstanding his genius as a system architect, didn’t know about that operator.For anyone else in the same boat, it works like this:
X = (condition) ? TrueValue : FalseValue
…which would expand to…
If (condition) THen X = TrueValue Else X = FalseValue
so that line above expands to:
If dr.IsDBNull(20) Then
 this.mExpires = DateTIme.MinValue
 this.mExpires = dr.GetDateTime(20)
End If

You’ve obviously got to be careful about using MinValue as a pseudo-null in case you actually want to use it somewhere. Not a problem with dates though, as SQL server can’t store a date of 1/1/1 anyway.

This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s