当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - DateTime2 error when I'm not using DateTime2

问题描述:

I'm getting this error when I run my create action on my controller :The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value"

Here is my Domain class:

public class MyEntity

{

public Guid Id {get; set;}

public string Name {get; set;}

public DateTime DateAdded {get; set;}

}

In the controller "POST" create actions I have this:

[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();

}

I'm not sure where the datatime2 is coming from.

网友答案:

Entity Framework, when modeling a SQL Server database, considers all date fields of type DateTime2.

So if, in your SQL Server database, a field is actually defined as a DateTime, you would get an out of range issue when you leave a date empty or when you specify another value that is in-range for DateTime2 but out of range for DateTime. Entity Framework itself doesn't catch this problem because it just assumes DateTime2.

The solution is to check that you have filled in values for all date fields and that they are within range.

网友答案:

I fixed this. I forgot/over looked I had an "DateChange" field

This now works

public class MyEntity
{
    public Guid Id {get; set;}
    public string Name {get; set;}
    public DateTime DateAdded {get; set;}
    public DateTime DateChanged {get; set;}
}

In the controller "POST" create actions I have this:

[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(); 
}

Still not sure why it give the conversion of a datetime2 error for.

分享给朋友:
您可能感兴趣的文章:
随机阅读: