在控制器上运行创建操作时,我收到此错误:将datetime2数据类型转换为datetime数据类型导致值超出范围。“
下面是我的Domain类:
public class MyEntity
{
public Guid Id {get; set;}
public string Name {get; set;}
public DateTime DateAdded {get; set;}
}在控制器"POST“创建操作中,我有以下内容:
[HttpPost]
public ActionResult Create(MyEntity entity)
{
entity.Id = Guid.NewGuid();
entity.DateAdded = DateTime.Now;
// the name will be added from the view
db.MyContext.Add(entity);
db.Save();
}我不确定datatime2是从哪里来的。
发布于 2013-05-28 22:25:00
实体框架在对SQL Server数据库建模时,会考虑DateTime2类型的所有日期字段。
因此,如果在SQL Server数据库中将某个字段实际定义为DateTime,则当您将日期保留为空时,或者当您指定的另一个值在DateTime2的范围内但超出DateTime的范围时,就会出现范围外的问题。实体框架本身并没有捕捉到这个问题,因为它只是假设了DateTime2。
解决方案是检查您是否已为所有日期字段填写了值,以及它们是否在范围内。
发布于 2013-05-28 22:25:12
我解决了这个问题。我忘记/忽略了我有一个"DateChange“字段
这现在起作用了
public class MyEntity
{
public Guid Id {get; set;}
public string Name {get; set;}
public DateTime DateAdded {get; set;}
public DateTime DateChanged {get; set;}
}在控制器"POST“创建操作中,我有以下内容:
[HttpPost]
public ActionResult Create(MyEntity entity)
{
entity.Id = Guid.NewGuid();
entity.DateAdded = DateTime.Now;
entity.DateChanged = DateTime.Now;
// the name will be added from the view
db.MyContext.Add(entity);
db.Save();
}仍然不确定为什么它会给出一个datetime2错误的转换。
https://stackoverflow.com/questions/16794221
复制相似问题