Reputation: 9298
I have a function that returns a date from a stored procedure, and it all works great til the value is NULL, how can I fix this so it works with null aswell?
public DateTime? GetSomteDate(int SomeID)
{
DateTime? LimitDate= null;
if (_entities.Connection.State == System.Data.ConnectionState.Closed)
_entities.Connection.Open();
using (EntityCommand c = new EntityCommand("MyEntities.GetSomeDate", (EntityConnection)this._entities.Connection))
{
c.CommandType = System.Data.CommandType.StoredProcedure;
EntityParameter paramSomeID = new EntityParameter("SomeID", System.Data.DbType.Int32);
paramSomeID.Direction = System.Data.ParameterDirection.Input;
paramSomeID.Value = SomeID;
c.Parameters.Add(paramSomeID);
var x = c.ExecuteScalar();
if (x != null)
LimitDate = (DateTime)x;
return LimitDate.Value;
};
}
Upvotes: 0
Views: 3199
Reputation: 39329
after this line:
var x = c.ExecuteScalar();
you can do this:
return x as DateTime?
If x
is a DateTime value, then it will return that datetime, else (null, DbNull.Value) it will return null.
Upvotes: 5
Reputation: 755073
Well, you just need to pay attention to this code snippet:
DateTime? LimitDate= null;
.....
var x = c.ExecuteScalar();
if (x != null)
LimitDate = (DateTime)x;
return LimitDate.Value;
You initialize LimitDate
to NULL, and if the value "x" returned from ExecuteScalar
is NULL, you don't do anything - and consequently, you shouldn't be calling
return LimitDate.Value
on it, after all LimitDate IS NULL
in this case! Or you need to initialize the LimitDate
variable to non-NULL value.....
You need something like this:
if(LimitDate != null)
return LimitDate.Value;
else
return null;
Upvotes: 0