简体   繁体   中英

Type conversion in C# for SQL data

I have a DataTable which is filled from a SQL database. Values are returned as object type (also the Calculate function returns object as well for some reason), so I need to convert them to proper type. It makes the code so complicated.

Like this:

 double value;

 foreach (DataRow row in sampleDataTable.Rows)
 {
     value +=  (double)Global.Calculate(Convert.ToDouble(Global.dbNullCheck(row["value1"], 0)) / Convert.ToDouble(row["value2"]), 2);
 }

I can write above code as:

 double sum;
 double value1;
 double value2;

 foreach (DataRow row in sampleDataTable.Rows)
 {
     value1 = Convert.ToDouble(Global.dbNullCheck(row["value1"], 0);
     value2 = Convert.ToDouble(row["value2"]);
     sum +=  (double)Global.Calculate(value1 / value2, 2);
 }

But of course, it is still not clear and I am doing something wrong. I need to check all values if they are DBNull and after that I need to convert them. Any ideas how can I improve this type of code? It's all around my code:)

Is there a good way to handle SQL data?

Don't think in terms of "convert". These objects are already the types you want; it's just the ADO.Net library can't know in advance what type to use. So instead of a conversion, which can be relatively slow, you need a cast .

Additionally, in general you don't want to think initially in terms of individual columns. Instead, define a class object to represent each row. Then create a function that accepts a DataRow as an argument and returns an instance of this new class as a result. This function will need to know what to do with individual columns, but the larger foreach loop (or similar) should just be calling this function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM