Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable types in strongly-typed datatables/datasets - workarounds?

Tags:

Strongly-typed DataTables support "nullable" field types, except that the designer will not allow you change the setting to "allow nulls" for any value type fields. (ie: String types allow nullable, but int's do not).

The workaround is to call IsMyFieldNull() any time you want to get Myfield. If you access MyField when it does contain a null, it throws an eception.

This is a massive headache, in addition to causing many runtime bugs when a null showing up can cause your app to crash. I've complained to microsoft for years about this, yet every new release of visual studio still does not allow nullable value types to be used.

My question: Anyone know of a fancy extension method(s) that could be used to work around this major shortcoming?

like image 542
Brady Moritz Avatar asked Jul 29 '10 21:07

Brady Moritz


1 Answers

If you are using .Net 3.5 or higher, may be these extensions might be of use to you: http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.field.aspx

According to the documentation, it fully supports nullable types. It allows you to use constructs like

MyRow.Field<int?>("MyField")  

and if you assign it to or from an existing variable of the correct type, the compiler can infer the type automatically and you can leave out the type specifier, making it as short as

int? myVar = MyRow.Field("MyField"); MyRow.Field("MyField") = myVar; 

Still not perfect, but a lot more legible than having to use IsMyFieldNull() etc everywhere.

Oh and if you want to be more on the safe side regarding misspelling column names, you can use things like

MyRow.Field(MyTable.MyFieldColumn) 

Don't forget to add a reference to System.Data.DataSetExtensions.

like image 170
M-Peror Avatar answered Oct 11 '22 08:10

M-Peror