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

asp.net-mvc c# datetime entity-framework

Question

I've got a controller.

[HttpPost]
public ActionResult Create(Auction auction)
{
    var db = new EbuyDataContext();
    db.Auctions.Add(auction);
    db.SaveChanges();
    return View(auction);
}

a case:

public class Auction
{
        public long Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public decimal StartPrice { get; set; }
        public decimal CurrentPrice { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }}
}

also a view

@model Ebuy.Website.Models.Auction
@using (Html.BeginForm())
{
    <p>
        //All the information fields...
        @Html.LabelFor(model => model.EndTime)
        @Html.EditorFor(model => model.EndTime)
    </p>
}

I get the following problem when I attempt to execute it:

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

The model-controller-view was taken verbatim from a book.

What format do I need to use when entering data into theEndTime field in order to prevent this error?

1
11
11/15/2015 9:04:36 PM

Accepted Answer

You actually didn't set those values correctly, so be sure to adjust them in accordance with your application's locale if you want to avoid the problem. (For example, dd/mm/yyyyen-GB , for mm/dd/yyyyen-US ).

Furthermore, it appears that your database has been configured to use adatetime2 not and a columndatetime column.

You may either:

A) Change the type from in the database bydatetime2 to datetime

B) Modify your Model's types so that they aredatetime2 by performing:

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

[Column(TypeName = "DateTime2")]
public DateTime EndTime { get; set; }
22
1/13/2014 9:30:40 PM

Popular Answer

When using EntityFramework and attempting to save an unassigened DateTime member to the database, I had the same issue. The member can be made nullable, as I discovered after reading the responses here. It worked when I gave it a try! So for those that require it, here is a code snap:

public Nullable<DateTime> MyDateTime { get; set; }

or

public DateTime? MyDateTime { get; set; }

Later, I may employ it as follows:

if(MyDateTime.HasValue)
{
    DoBlaBla(MyDateTime.Value);
}

or simply give it a value as if nothing had happened.

MyDateTime = DateTime.Now;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow