C# 从标量存储过程返回可为空的datetime

C# 从标量存储过程返回可为空的datetime,c#,entity-framework,C#,Entity Framework,我有一个从存储过程返回日期的函数,它在值为NULL之前工作得很好,我如何修复它,使它也能使用NULL public DateTime? GetSomteDate(int SomeID) { DateTime? LimitDate= null; if (_entities.Connection.State == System.Data.ConnectionState.Closed) _entities.Connection

我有一个从存储过程返回日期的函数,它在值为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;

        };
    }

那么,您只需要注意以下代码片段:

DateTime? LimitDate= null;

.....

var x = c.ExecuteScalar();

if (x != null)
    LimitDate = (DateTime)x;

return LimitDate.Value;
您将
LimitDate
初始化为NULL,如果从
ExecuteScalar
返回的值“x”为NULL,则不执行任何操作-因此,您不应该调用

return LimitDate.Value
毕竟,在这种情况下,
LimitDate是空的
!或者您需要将
LimitDate
变量初始化为非空值

你需要这样的东西:

if(LimitDate != null)
    return LimitDate.Value;
else
    return null;

那么,您只需要注意以下代码片段:

DateTime? LimitDate= null;

.....

var x = c.ExecuteScalar();

if (x != null)
    LimitDate = (DateTime)x;

return LimitDate.Value;
您将
LimitDate
初始化为NULL,如果从
ExecuteScalar
返回的值“x”为NULL,则不执行任何操作-因此,您不应该调用

return LimitDate.Value
毕竟,在这种情况下,
LimitDate是空的
!或者您需要将
LimitDate
变量初始化为非空值

你需要这样的东西:

if(LimitDate != null)
    return LimitDate.Value;
else
    return null;
在这一行之后:

var x = c.ExecuteScalar();
您可以这样做:

return x as DateTime?
如果
x
是一个DateTime值,那么它将返回该DateTime,否则(null,DbNull.value)它将返回null。

在此行之后:

var x = c.ExecuteScalar();
您可以这样做:

return x as DateTime?

如果
x
是一个DateTime值,那么它将返回该DateTime,否则(null,DbNull.value)它将返回null。

您也可以检查此
x!=DbNull.Value,我想。

您也可以检查这个
x!=DbNull.Value
,我想。

如果你能说出返回值为NULL时会发生什么,那会有帮助。如果你能说出返回值为NULL时会发生什么,那会有帮助。仅供未来谷歌参考:
return LimitDate?.Value现在执行与上一个代码段相同的操作。它被称为.FYI未来谷歌:
returnlimitdate?.Value现在执行与上一个代码段相同的操作。它叫“世界杯”。