从标量存储过程返回可为空的日期时间

Las*_*vik 0 c# entity-framework

我有一个函数,从存储过程返回一个日期,它一切正常,直到值为NULL,我怎么能解决这个问题,所以它适用于null呢?

    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;

        };
    }
Run Code Online (Sandbox Code Playgroud)

Han*_*ing 5

在这一行之后:

var x = c.ExecuteScalar();
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

return x as DateTime?
Run Code Online (Sandbox Code Playgroud)

如果x是DateTime值,那么它将返回该datetime,否则(null,DbNull.Value)它将返回null.