Conversion of a Datetime2 Data Type to a Datetime Data Type Results Out-Of-Range Value

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated

The datetime column "DateAdded" is marked Not Nullable in sql.

Option 1 (change controller):

[HttpPost]
public ActionResult Create(Movie movie)
{
//setdate
movie.DateAdded = Datetime.Now;
_context.Movies.Add(movie);
_context.SaveChanges();

return RedirectToAction("Index", "Movies");
}

Option 2 (change model)

public class Movie 
{
public int Id { get; set; }

[Required]
[StringLength(255)]
public string Name { get; set; }

public DateTime DateAdded { get; set; } = Datetime.Now;

[Display(Name = "Release Date")]
public DateTime ReleaseDate { get; set; }

[Display(Name = "Number in Stock")]
public byte NumberInStock { get; set; }

public Genre Genre { get; set; }

[Display(Name = "Genre")]
[Required]
public byte GenreId { get; set; }
}

How to fix The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

You did not set a value for SolvedDate, so the default value which is 01\01\01 will be sent to the database, which causes the error.

If you want to have SolvedDate with null value, you should define it as Nullable date(DateTime?) because DateTime is a struct and cannot be set to null.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value exception

datetime2 coveres a larger range than datetime.

datetime2:

Date range 0001-01-01 through 9999-12-31

datetime:

Date range January 1, 1753, through December 31, 9999

Date="12-03-19" probably converts to year 12 (or 19). The solution could be using DateTime for the Date property:

public class TimeOutJustification
{
public DateTime Date { get; set; }
...
}

The conversion of a datetime2 data type to a datetime data type Error

The error is because you haven't actually set those values correctly, make sure you set them depending on your applications locale. (e.g. dd/mm/yyyy for en-GB, mm/dd/yyyy for en-US).

It also looks like your database has been set up to use a datetime2 column and not a datetime column.

You can either:

A) Modify the database to change the type from datetime2 to datetime

B) Change the types in your Model to be datetime2, by doing:

[Column(TypeName = "DateTime2")]
public DateTime StartTime { get; set; }

[Column(TypeName = "DateTime2")]
public DateTime EndTime { get; set; }


Related Topics



Leave a reply



Submit