I am parsing XML (LINQ to XML) and I am using a nullable type (int? and decimal?) in cases where the element / attribute is empty. However, when building my collection to pass to the DB (Using TVP) I don’t know how to handle the cases where the value is actually null. I can’t pass a null into the SqlDataRecord SetInt32 or SetDecimal and I don’t want to set to zero….I actually want it to be null.
Telling me no overload for int?
Count below is a nullable type (int? Count)
SqlDataRecord rec = new SqlDataRecord(
new SqlMetaData("Name", SqlDbType.VarChar, 50),
new SqlMetaData("Type", SqlDbType.VarChar, 50),
new SqlMetaData("Count", SqlDbType.Int));
rec.SetString(0, dm.Name);
rec.SetString(1, dm.Type);
rec.SetString(2, dm.Count);
Any ideas how to handle this without passing zero (maintaining the null)?
Extension method:
or, to use
SetSqlInt32as suggested by D Stanley:Note, 9 Dec 2013: Returning to this answer because of a comment, I noticed a small opportunity for improvement, based on Eric Lippert’s series on nullable micro-optimizations, which can be found at http://ericlippert.com/2012/12/20/nullable-micro-optimizations-part-one/.
In brief, while the
Valueproperty requires less typing and is therefore arguably more optimal for the programmer, it has to throw an exception if HasValue is false. On the other hand, theGetValueOrDefault()method is a simple field access. Because of this,GetValueOrDefault()requires fewer instructions and is more likely to be inlined, so it is more optimal for the compiler and the processor.