我有一个5列的数据表,其中一行被数据填充,然后通过事务保存到数据库。

保存时,返回一个错误:

将datetime2数据类型转换为datetime数据类型会导致值超出范围

它暗示,正如阅读,我的数据表有一个类型的DateTime2和我的数据库一个DateTime;这是错误的。

date列设置为DateTime,如下所示:

新数据专栏(“myDate, Type.GetType”)

问题

是否可以在代码中解决这个问题,或者是否必须在数据库级别上更改某些内容?


当前回答

看看下面两个: 1)该字段没有NULL值。例如:

 public DateTime MyDate { get; set; }

替换:

public DateTime MyDate { get; set; }=DateTime.Now;

2)重新创建数据库。例如:

db=new MyDb();

其他回答

检查DB中的req格式。例如我的DB有默认值或Binding (((1)/(1))/(1900))

System.DateTime MyDate = new System.DateTime( 1900 ,1, 1);

当我想用ASP编辑一个页面时,我看到了这个错误。净MVC。我没有问题,而创建,但更新数据库使我的DateCreated属性超出范围!

当您不希望您的DateTime属性为空,并不想检查它的值是否在sql DateTime范围(和@Html。HiddenFor没有帮助!),只需在相关类(控制器)中添加一个静态DateTime字段,并在GET操作时给它一个值,然后在POST执行它的工作时使用它:

public class PagesController : Controller
{
    static DateTime dateTimeField;
    UnitOfWork db = new UnitOfWork();

    // GET:
    public ActionResult Edit(int? id)
    {
        Page page = db.pageRepository.GetById(id);
        dateTimeField = page.DateCreated;
        return View(page);
    }

    // POST: 
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Page page)
    {
        page.DateCreated = dateTimeField;
        db.pageRepository.Update(page);
        db.Save();
        return RedirectToAction("Index");

    }
}

已经有很多好的答案了。我想展示一种使用实体框架core fluent api来解决这个问题的方法。 大多数情况下,错误发生在默认情况下生成DateTime值时,因此您需要覆盖DataContext中的OnModelCreating,并在您的特定实体的属性中手动添加默认值,以便EF能够正确地转换到数据库,如下所示:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<MyEntity>(entity =>
        {
            entity.ToTable("MyTable");

            entity.Property(e => e.MyColumnDateTime)
                .HasDefaultValueSql("GETDATE()");
        });

        OnModelCreatingPartial(modelBuilder);
    }

在我的例子中,当为Nullable DateTime列显式分配NULL值时,然后尝试保存更改。这个错误将会弹出。

继承的datetime属性有问题

当不可为空的日期字段在插入/更新时值为null时,通常会显示此错误消息。其中一个原因可能是遗传。

如果你的日期是从基类继承的,你不做映射EF将不会读取它的值。

欲了解更多信息: https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines