Tuesday 19 February 2008

XSD Null values Problem

Source: http://www.socalmp.com/blog/template_permalink.asp?id=91

For columns not defined as System.String, the only valid value is (Throw exception)

For handeling NULLS in a typed DataSet there are several solutions which are all combersome if the datatype is anything other than a string.
In Visual Studio once you define the typed dataset you can adjust the properties of the column values by clicking on the column in the .xsd GUI.

This allows you to set the datatype and how to handle NullValue. If the datatype is System.String then you can change the NullValue to empty(""), null(DBNull) or throw exception. The exception displays an ugly error message in the browser and provides little information on how to correct the issue. (The value for column '*' in table '*' is DBNull) or (System.InvalidCastException: Specified cast is not valid.)

If your datatype is INT, Decimal, etc.. you have to use error handeling in the script to workaround this issue. Ideally you would expect MS VS2005 to allow you to set the null value to (0), (0m), etc... but that bug is still not fixed.
Some blogs suggest to change the .cs file to set the value using an if statement. That will work but it will also get overwritten wehn you uspdate the file with another dataset.

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=174108&SiteID=1

Fortunately when the Typed Dataset was created it generated a method to return a boolean value if the column data was Null.


foreach (BedroomTvRecord.SelectBedroomTvRecordRow row in table)
{
BedroomTv record = new BedroomTv();
record.Biography = row.AboutMe;
record.Country = row.Country;
record.DateOfBirth = row.IsDOBNull() ? (DateTime?)null : row.DOB;
record.Email = row.Email;
record.FirstName = row.FirstName;
record.LastName = row.LastName;
record.MemberId = row.MemberID;
record.PhoneNumber = row.MobileNumber;
record.Thumbnail = row.ThumbnailImage;
record.Username = row.Username;
list.Add(record);
}

No comments: