【问题标题】:DateTime2 is driving me crazyDateTime2 让我发疯
【发布时间】:2012-08-09 20:43:38
【问题描述】:

我在我的项目 .NET 中使用 EF 4(模型优先),我在使用 DateTime 字段时遇到了难题。

当我使用SaveChanges() 时会抛出此异常:

System.Data.SqlClient.SqlException :将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围。

我尝试使用:

System.Globalization.CultureInfo enGB = new System.Globalization.CultureInfo("en-GB");

但没有新的事情发生。如果今晚不修好,我会炸毁我的电脑。

我需要帮助,我不想炸毁我的电脑 =( 1 周尝试解决它但没有成功

这是我的代码:

protected void btnSave_Click(object sender, EventArgs e)
{
        int id = Convert.ToInt32(Request.QueryString["id"]);
        ModeloContainer ctx = new ModeloContainer();
        Cliente cli = ctx.Cliente.Where( cl => cl.IdCliente == id).First();
        Contrato c = new Contrato();

        c.Descricao = this.txtDescricao.Text;
        c.FaturarPara = this.ddlFaturarPara.SelectedValue;
        c.Tolerancia =  Convert.ToInt32(this.txtSuspenderContratoEm.Text);
        c.PeriodoPagto = this.ddlPeriodoPagamento.SelectedValue;

       // DateTime dtExpiracao = this.txtExpiraEm.Text.Trim() == "" ?                                                                       Convert.ToDateTime("01/01/0001") : Convert.ToDateTime(this.txtExpiraEm.Text.Trim());
        DateTime dt = DateTime.Now;
        System.Globalization.CultureInfo enGB = new System.Globalization.CultureInfo("en-GB");
        dt = Convert.ToDateTime(dt, enGB);

        c.ExpiraEm = dt; //Here is the problem! but I no have idea how fix it

        ctx.AddToContrato(c);
        ctx.SaveChanges();
        this.SalvarServiços(c.IdContrato);
}

我知道,这里有很多这样的问题,但没有一个能解决我的问题。

我想在 TextBox 中插入这样的日期:09/08/2012

【问题讨论】:

  • 试试this post,如果这对您没有帮助,您可以发布您的模型/
  • 您的实体中是否还有其他不可为空的DateTime 字段?如果是,这是您的问题的根源,因为 EF 将 1/1/0001 发送到该列。您还可以使用 SQL 分析器检查 EF 尝试将哪些值保存到数据库。

标签: entity-framework datetime2


【解决方案1】:

我认为您的ExpiraEm 专栏没有任何问题。

我怀疑您有另一个(或超过 1 个)不可为空的日期时间字段,并且由于您没有为它们提供任何值,EF 将为它们传递 01/01/0001,这是不可接受的由 SQL Server(SQL Server 可接受的最短日期为 1753 年 1 月 1 日)。所以你得到了这个 SQL 异常。

herehere也遇到过类似情况。

【讨论】:

    猜你喜欢
    • 2011-05-30
    • 2012-11-02
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2012-03-14
    • 2021-04-20
    相关资源
    最近更新 更多