Monday, June 2, 2008

Linq to SQL Bug - "System.FormatException: String must be exactly one character long."

Ran into a very annoying bug today. When I tried to use Linq to SQL to read values from a rather unexciting table, the site threw up with

System.Web.HttpUnhandledException: Exception of type
     'System.Web.HttpUnhandledException' was thrown. ---> 
System.FormatException: String must be exactly one character long.

 It took a while to narrow it down, but it turned out to be a field in the table that was defined as NVARCHAR(1). The LINQ to SQL mapping was System.Char. All the other NVARCHAR fields were mapped to System.String.

Not much out there on the forums about it when I did a casual google search either so I thought I'd post about it here.

I did find it listed as an active bug on the Microsoft Connect site here.

The problem is that Visual Studio's LINQ to SQL designer incorrectly maps this to char instead of string. Since char types cannot be "empty" you will get an error at runtime if any of your columns contain empty values. Null will work fine though.

The easy work around is to just manually toggle the type to System.String in Visual Studio's property window. If that doesn't work for you, you could change the column to char(1) in the DB instead and just not put empty strings in there.

In my case, I'm using a middle initial field. I like to treat null in my database as "undefined"... meaning that no value was specified at all or the question hasn't been answered. This is different from empty... empty would mean that the question was asked, and the answer was "no value". The difference is subtle, but important sometimes.


No comments:

Post a Comment