I am getting this error:
"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 view that interacts with users has the following relevant code:
@Html.LabelFor(model => model.BirthDate)
@Html.TextBoxFor(model => model.BirthDate, new { size = "50", @type = "date", @class = "AddMemberControls" })
The texbox where the user has to input date, says "mm/dd/yyyy" (and it shows a calender where the user can pick a date)
The controller method looks like this:
public ActionResult AddMember(string firstName, string lastName, DateTime birthDate, int age, string sportType)
{
var member = new Member() { FirstName = firstName, LastName = lastName, Age = age, SportType = sportType, BirthDate = birthDate };
coloContext.Members.Add(member);
coloContext.SaveChanges();
return View();
}
And model:
[Column(TypeName = "datetime2")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime BirthDate { get; set; }
If for example the user chooses the date 05/01/18
, then when debugging, and checking the birthdate parameter, it says 01-May-18 12:00:00 AM
I guess the issue is that it writes "May", and the database doesn't know how to save that?
I see there is a lot about this issue on the internet, and several attempts on a solution, but unfortunately, neither has worked for me yet.
I have tried:
Add annotation with column typename
[Column(TypeName = "datetime2")]
Making Datime nullabe in my model (Which several solutions suggested). But this solution does not make much sense to me. Especially when I know that this parameter can not be null
public DateTime? BirthDate { get; set; }
Tried to parse the DateTime, hoping that it will get rid of the "May". If possible though, I'd like the date to be saved in that format.
DateTime test = DateTime.parse(birthDate.ToString())
Some suggested changing to DateTime2, but there is no object called DateTime2? I tried anyway, but got an error on this
public DateTime2 BirthDate { get; set; }
And a few other solutions that I forgot.