What’s a good way to handle unqualified values when creating entity to insert data into SQL? I tried using DBnull (failed) and a few different conditional statements (works but very verbose)

My data is in CSV. I run the string through an extension that removes weird values like "–", "++", "/", "+/-" but then I'm left with empty values. I simple wanted to send a null value to the DB and even thought my columns are nullable types, that doesn't work.

I considered:

myEntity.Qty = valueArray[2].All(x=>char.IsDigit(x)) ? int.Parse(valueArray[2]) : int.MaxValue; 

But that wouldn't work for decimals and also I didn't like the idea of using int.MaxValue. But simply saying

 myEntity.Change_Pct = decimal.TryParse(valueArray[2], out d) ? d : null; 

didn't work. I could replace null with decimal.MaxValue but isn't that going to waste space in my database? So I decided to use

if(valueArray[2]!="") myEntity.Change_Pct = decimal.Parse(valueArray[2]); 

This works by simply leaving the missing data fields as nulls. But since I have 35 columns, that's a lot of IF statements for each line.

So I'm wondering what's an easy way of achieving the same with less roundabout way.

A different question relating to same problem is when I'm using TryParse I did something like this

decimal d; myEntity.Col4 = decimal.TryParse(valueArray[3], out d) ? d : 999999M; myEntity.Col5 = decimal.TryParse(valueArray[8], out d) ? d : 999999M; 

I thought the "out d" meant that the parameter should be uninitialized…but it worked fine as far as I could tell. So is that fair use or am I doing it wrong.

by pope_says via /r/csharp

Leave a Reply