Reputation:
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.
Upvotes: 1
Views: 445
Reputation:
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.
Upvotes: 0
Reputation: 33139
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.
Upvotes: 1