AS part of an import I'm writing I'm using parameterised values, however the database i'm exporting to cannot handle NULL values, so I need to find a way to handle NULL values.
The closest I've gotten is:
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}
and A similar thing with SQLDateTime
if (tenantexportReader.GetDateTime(9).ToShortDateString().Equals(null))
{
tenantimportCommand.Parameters["TENSDATE"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["TENSDATE"].Value = tenantexportReader.GetDateTime(9).ToShortDateString();
}
However this does not appear to work, instead I receive the following:
Message=Data is Null. This method or property cannot be called on Null values.
Instead of
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
you should probably use
if (tenantexportReader.IsDbNull(8))
Since the value in the database is NULL (which is DbNull.Value in c#), I assume that GetSqlMoney and GetSqlDateTime throw the exception you received. DbNull.Value cannot be converted to SqlMoney or DateTime.
Check if the value is null via IsDbNull before calling GetSqlMoney or GetSqlDateTime.
So your final if statements should look something like this:
if (tenantexportReader.IsDbNull(8))
{
tenantimportCommand.Parameters["PRICEASK"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}
Why would you assign a string to a monetary value???
Probably what you would want to do is like this:
var priceFinal = tenantexportReader.GetSqlMoney(8);
tenantimportCommand.Parameters["PRICEFINAL"].Value = (decimal)(priceFinal.IsNull ? 0 : priceFinal);
I really don't understand why you set it to "0.00" (string) when it is null and to a decimal value when it is not null.
And also for date/datetime values, again, why do you ever use string conversions and invite errors? Simply pass a date as a datetime.
Related
I need to return a NULL or Blank value for Apvl_Lvl_Id if the SQL result returns NULL as the integration this passes the Apvl_Lvl_Id value to can't handle a value if it doesn't match an existing value for that instance.
I can't figure out what I'm missing, hoping someone can offer some pointers. Hope the below code is enough for an example.
while (dr.Read())
{
if(dr.IsDBNull(Apvl_Lvl_Id))
{
int? Apvl_Lvl_IdNULL;
Apvl_Lvl_Id = Apvl_Lvl_IdNULL;
}
else
{
Apvl_Lvl_Id = dr.GetInt32(0);
}
}
Sorry, but that code makes little sense. Apparently, Apvl_Lvl_Id is supposed to be the column ordinal - effectively the zero-based count of the column in a row - that you check for being DBNull. Then you are trying to assign the actual column's value to that ordinal? Apart from that, there is just no way you can assign null to an int. Introduce a separate variable, say, Apvl_Lvl_Value, make it an Nullable<int> (or int?) and assign the the column's value as required (actual value or null).
In "short", the code should more like this:
while (dr.Read())
{
int? Apvl_Lvl_Value;
// Check if the value of the column with the ordinal Apvl_Lvl_Id is DBNull
if(dr.IsDBNull(Apvl_Lvl_Id))
{
// If so, use .NET "null" for the rest of the logic.
Apvl_Lvl_Value = null;
}
else
{
// Use the actual columns (non-NULL) value.
Apvl_Lvl_Value = dr.GetInt32(Apvl_Lvl_Id);
}
// Do something with the column's value, stored in Apvl_Lvl_Value
}
Now, some things here are guesswork which are not really clear otherwise from your question, but generally, the above is a "pattern" by which one would use IsDBNull() and
a Get*() method together.
And why don't you just set
Apvl_lvl_Id = null;
Possible Duplicate:
C# ?: Conditional Operator
statement first:
if(dr["AskingPriceFrom"]!=System.DBNull.Value)
objFilters.AskingPriceFrom=Convert.ToDecimal(dr["AskingPriceFrom"]);
else
objFilters.AskingPriceFrom=null;
statement second:
objFilters.AskingPriceFrom=Convert.ToDecimal(
dr["AskingPriceFrom"]!=System.DBNull.Value ? dr["AskingPriceFrom"] : null
);
What is difference between these two statements?
In first statement, if value is empty in if-else condition, then it stores null value correctly; but, if value is empty in the second condition, then instead of storing null value it stores 0. AskingPriceFrom is a get-set field stores decimal value. I tried to convert only dr["AskingPriceFrom"] after the question mark but the statement gives me an error.
Is there any way to protect null value from converting in decimal?
Apparently Convert.ToDecimal(null) == 0
//Edit: This should work
objFilters.AskingPriceFrom =
(dr["AskingPriceFrom"] != System.DBNull.Value) ?
Convert.ToDecimal(dr["AskingPriceFrom"]) : null;
It's because Decimal is not nullable. You should cast to decimal? so that when you convert a null to that type it will not return the default value 0 but instead return null.
in the inline version(ternary)
if it is null you will get:
objFilters.AskingPriceFrom = Convert.ToDecimal(null);
this will probably result an error.
You should read Convert.ToDecimal documentation here http://msdn.microsoft.com/en-us/library/e6440ed8.aspx.
Convert.ToDecimal returns decimal or throws exception, but in your case you need return type as Nullable<decimal>.
You can use code like this:
decimal? result;
if (Convert.IsDBNull(dr["AskingPriceFrom"]))
{
result= null;
}
else
{
result = dr.GetDecimal(reader.GetOrdinal("AskingPriceFrom"));
}
Thanks a lot to https://stackoverflow.com/users/1336654/jeppe-stig-nielsen. This is working properly.
objFilters.AskingPriceFrom = dr["AskingPriceFrom"] != System.DBNull.Value ? Convert.ToDecimal(dr["AskingPriceFrom"]) : (decimal?)null;
I would like to check if the decimal number is NULL or it has some value, since the value is assigned from database in class object:
public decimal myDecimal{ get; set; }
and then I have
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
I am trying:
if (rdrSelect[23] != DBNull.Value)
{
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
}
But I am getting this:
the result of the expression is always 'true' since a value of type
'decimal' is never equal to null
How can I check if that decimal number has some value?
A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue
you can use this code
if (DecimalVariable.Equals(null))
{
//something statements
}
decimal is a value type in .NET. And value types can't be null. But if you use nullable type for your decimal, then you can check your decimal is null or not. Like myDecimal?
Nullable types are instances of the System.Nullable struct. A nullable
type can represent the normal range of values for its underlying value
type, plus an additional null value.
if (myDecimal.HasValue)
But I think in your database, if this column contains nullable values, then it shouldn't be type of decimal.
I've ran across this problem recently while trying to retrieve a null decimal from a DataTable object from db and I haven't seen this answer here. I find this easier and shorter:
var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;
This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.
Assuming you are reading from a data row, what you want is:
if ( !rdrSelect.IsNull(23) )
{
//handle parsing
}
Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).
Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue
If you're pulling this value directly from a SQL Database and the value is null in there, it will actually be the DBNull object rather than null. Either place a check prior to your conversion & use a default value in the event of DBNull, or replace your null check afterwards with a check on rdrSelect[23] for DBNull.
You can also create a handy utility functions to handle values from DB in cases like these.
Ex. Below is the function which gives you Nullable Decimal from object type.
public static decimal? ToNullableDecimal(object val)
{
if (val is DBNull ||
val == null)
{
return null;
}
if (val is string &&
((string)val).Length == 0)
{
return null;
}
return Convert.ToDecimal(val);
}
I have to modify a Visual Studio 2010 C# project that works with Oracle, looking at some code I've found a function that returns a List<> with values loaded from a database stored procedure (cursor)
while (myIDataReader.Read())
{
// OK
myTable.myStringField = myIDataReader["TableStringField"].ToString();
// ¿?
myTable.myIntField =
Convert.ToInt32((myIDataReader["TableIntField"] == DBNull.Value) ? null : myIDataReader["myTableField"]);
}
Everything's ok, just want to know, what conditions are given when assign myTable.myIntField, I know this column is nullable, but I don't get the syntax, if someone can explain I'll be thankful
You are talking about this line?
myTable.myIntField =
Convert.ToInt32((myIDataReader["TableIntField"] == DBNull.Value) ? null : myIDataReader["myTableField"]);
If you break that statement apart, you have a type of conditional, often called the Ternary operator, explained here.
conditional ? if_true_do_this : if_false_do_this
It is really just a different syntax for:
if(conditional) {
if_true_do_this;
} else {
if_false_do_this
}
After that, it simply passes the result to Convert.ToInt32() to turn it from a string into an int.
So that line of code is just a more concise version of this:
if(myIDataReader["TableIntField"] == DBNull.Value)
{
myTable.myIntField = Convert.ToInt32(null);
}
else
{
myTable.myIntField = Convert.ToInt32(myIDataReader["myTableField"]);
}
The syntax above works correctly and it means:
TableIntField could contains a database null.
This is expressed in NET via the DBNull object and its Value field.
The code checks if the TableIntField contains the DBNull.Value via C# ternary operator.
If the checks result in a true condition, a null is used as argument for Convert.ToInt32 and this, according to MSDN documentation, result in a zero value assigned to myTable.myIntField.
I'm trying to reuse the same code I've always used but now it is encountering an error.
I'm looping through various user tables, and in there I do this:
DateTime dcdt = (DateTime)u.DateCreated;
DateTime lldt = (DateTime)u.LastLogon;
userRow["DateCreated"] = dcdt.ToShortDateString();
inside the loop. I get the error:
System.InvalidOperationException: Nullable object must have a value.
The error highlights "lldt" line, instead of "dcdt" which comes first. That is strange in and of itself. Both these fields in the database "allow nulls" is checked. And they both could be null or neither might be null.
The two values are both listed as DateTime? types through intellisense.
I don't understand why ASP.NET refuses to allow me to output blank for null dates. If it is empty/null, then logic would suggest that ASP.NET should just print nothing.
How else am I suppose to output null dates? I tried adding if statements to prevent trying to cast null DateTimes, but it doesn't help, it makes no sense.
As you've said, the data type of u.LastLogon is DateTime?. This means that it may or may not have a value. By casting to DateTime, you are requiring it to have a value. In this case, it does not.
Depending on what you're trying to do with it, you may want to check the HasValue property:
userRow["LastLogon"] = u.LastLogin.HasValue ?
(object) u.LastLogin.ToShortDateString() : DBNull.Value;
If your database LastLogon column is of DateTime type, then you should be able to do:
userRow["LastLogon"] = u.LastLogin.HasValue ?
(object) u.LastLogin.Value : DBNull.Value;
You need to do something like the following in your data access code:
DataTable dt = ExecuteSomeQuery() ;
object value = dt.Rows[0]["nullable_datetime_column"] ;
DateTime? instance = value != null && value is DateTime ? (DateTime?)value : (DateTime?)null ) ;
If the column returned is NULL, it will be returned as a System.DBNull, otherwise it will be returned as an instance of DateTime (or whatever the appropriate mapped type is — int, string, etc). Consequently, you need to check the type of object returned from the query before trying to cast it.
Looks like you are trying to call a method (dcdt.ToShortDateString()) on a DateTime? which doesn't have a value (it is, indeed, null). Try this:
dcdt.HasValue ? dcdt.ToShortDateString() : String.Empty;
EDIT (Just re-read the question): Also, don't try to convert to DateTime. Preserve the nullable.
EDIT #2 (based on comments):
Try this:
if (dcdt.HasValue)
{ userRow["DateCreated"] = dcdt.ToShortDateString(); }
else
{ userRow = DbNull.Value }
I saw that Dexter asked how he should go about it. Well, I would create an extension.
static class DateTimeExtensions
{
public static string ToString(this DateTime? dateTime, string format)
{
return dateTime.HasValue ? dateTime.Value.ToString(format) : String.Empty;
}
}
And then you can do:
DateTime? dt = null;
DateTime? dt2 = DateTime.Now;
Console.WriteLine(dt.ToString("dd-MM-yy"));
Console.WriteLine(dt2.ToString("dd-MM-yy"));
Note that I can call extension method on a nullable type if the object is null.
The problem is .NET null is not the same as SQL NULL. SQL Null is System.DBNull. So it is a [non-null] value in .NET.
Short answer
DateTime? dateTime = u.LastLogon?.ToShortDateString()