简体   繁体   中英

Return nullable datetime from scalar, stored procedure

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;

        };
    }

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.

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;

我认为您也可以检查此x != DbNull.Value

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