Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

datatable - C# DBNull and nullable Types - cleanest form of conversion

I have a DataTable, which has a number of columns. Some of those columns are nullable.

DataTable dt;  // Value set. 
DataRow dr;  // Value set. 

// dr["A"] is populated from T-SQL column defined as: int NULL 

What, then, is the cleanest form of converting from a value in a DataRow, to a nullable variable.

Ideally, I would be able to do something like:

int? a = dr["A"] as int?; 

Edit: Turns out you CAN do this, the side effect being that if your Schema types arn't ints, then this is ALWAYS going to return null. The answer by Ruben of using dr.Field<int?>("A") ensures type mismatches don't silently fail. This, of course, will be picked up by thorough unit tests.

Instead I'm usually typing something along the lines of:

int? a = dr["A"] != DBNull.Value ? (int)dr["A"] : 0; 

This is a bunch more keystrokes, but more importantly, there's more room for someone to stuff something up with a wrong keystroke. Yes, a Unit Test will pick this up, but I'd rather stop it altogether.

What is the cleanest, least error-prone pattern for this situation.

question from:https://stackoverflow.com/questions/1706405/c-sharp-dbnull-and-nullable-types-cleanest-form-of-conversion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The LINQ to DataSets chapter of LINQ in Action is a good read.

One thing you'll see is the Field<T> extension method, which is used as follows:-

int? x = dr.Field<int?>( "Field" );

Or

int y = dr.Field<int?>( "Field" ) ?? 0;

Or

var z = dr.Field<int?>( "Field" );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...