LINQ存储过程DATETIME NULL

时间:2010-02-12 12:02:22

标签: sql linq-to-sql

当我使用Linq和存储过程时,我得到了这个错误消息。当DateTime参数为NULL时,我收到此消息。我该怎么做才能解决这个问题?

ERRORMESSAGE Serverfel itillämpningsprogrammet。 SqlDateTime-spill:Detmåstevaramellan 1/1/1753 12:00:00 AM och 12/31/9999 11:59:59 PM。

C#中的代码块

protected void ButtonSearch_Click(object sender, EventArgs e)
{
    Postit p = new Postit(); 
    DateTime? dt;

    if(TextBoxDate.Text=="")
    {
        dt=null;
    }
    else
    {
        dt=System.Convert.ToDateTime(TextBoxDate.Text);
    }

    GridView1.DataSource = p.SearchPostit(TextBoxMessage.Text, TextBoxWriter.Text, TextBoxMailto.Text, System.Convert.ToDateTime(dt));  
    GridView1.DataBind();
}



public ISingleResult<Entities.SearchPostitResult> SearchPostit([Parameter
(DbType="VarChar(1000)")] string message, [Parameter(DbType="VarChar(50)")] string writer, [Parameter(DbType="VarChar(100)")] string mailto, [Parameter(DbType="DateTime")] System.Nullable<System.DateTime> date)
{           
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), message, writer, mailto, date);

return ((ISingleResult<Entities.SearchPostitResult>)(result.ReturnValue));

Procedure
ALTER PROCEDURE [dbo].[SearchPostit]
    (
    @message varchar(1000)='', 
    @writer varchar(50)='',
    @mailto varchar(100)='',
    @date Datetime=null
    )
AS
    SELECT P.Message AS Postit, P.Mailto AS 'Mailad till', P.[Date] AS Datum , U.UserName AS Användare  
    FROM PostIt P   

    INNER JOIN [User] U ON P.UserId=U.UserId

        WHERE   P.message LIKE '%'+@message+'%' 
AND     P.Mailto LIKE '%'+@mailto+'%'  
AND     (
                @date IS NULL 
            OR  P.Date = @date
        )
AND     U.UserName LIKE '%'+@writer+'%'
    GROUP BY P.Message, P.Mailto, P.[Date], U.UserName
}

3 个答案:

答案 0 :(得分:1)

您应该使用:

SqlDateTime.MinValue.Value 

而不是:

new DateTime(1753,01,01).

答案 1 :(得分:0)

通过为日期时间分配NULL

if(TextBoxDate.Text=="")
{
    dt=null;
}

您的转换语句将失败

System.Convert.ToDateTime(dt)

我不确定,但我认为使用了datetime的默认值(“0001/01/01”),因此查询将失败,因为此日期不会介于

之间
1/1/1753 12:00:00 AM och 12/31/9999

我建议您在没有从用户界面输入日期时为“dt”指定最短日期

if(TextBoxDate.Text=="")
{
    dt= new DateTime(1753,01,01);
}

[编辑]

调用存储时,所有你有todo都会删除冗余的Convert语句 程序

    GridView1.DataSource = p.SearchPostit(TextBoxMessage.Text, 
       TextBoxWriter.Text, TextBoxMailto.Text, dt);  
由于你已经将dt声明为DateTime?,因此它是多余的。

答案 2 :(得分:0)

ALTER PROCEDURE [dbo].[SearchPostit]
    (
    @message varchar(1000)='', 
    @writer varchar(50)='',
    @mailto varchar(100)='',
    @date Datetime=null
    )
AS
    SELECT P.Message AS Postit, P.Mailto AS 'Mailad till', P.[Date] AS Datum , U.UserName AS Användare  
    FROM PostIt P   

    INNER JOIN [User] U ON P.UserId=U.UserId

        WHERE   P.message LIKE '%'+@message+'%' 
AND     P.Mailto LIKE '%'+@mailto+'%'  
AND     ISNULL(@Date, 0) IN (P.Date, 0)
AND     U.UserName LIKE '%'+@writer+'%'
    GROUP BY P.Message, P.Mailto, P.[Date], U.UserName
}