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

后端 未结 9 1567
慢半拍i
慢半拍i 2020-12-30 08:45

I have a controller:

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


        
9条回答
  •  天命终不由人
    2020-12-30 08:47

    I also struck this problem.

    The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value is a very un-useful error that one receives.

    To resolve the problem I had to do the following (Using the above example):

    One can find the Package Manager Console from -> Tools -> Library Package Manager -> Package Manager Console

    I enabled Database Migrations in Package Manager Console -> Enable-Migrations

    Then added the below code in the Controller Class:

    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; }
    
    // My Edit to the code Start -->
    public Nullable StartTime { get; set; }
    public Nullable EndTime { get; set; }}
    // My Edit to the code Finish <--
    }
    

    Then in the Models Class:

    [HttpPost]
    
    // My Edit to the code Start -->
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:d}")]]
    // My Edit to the code Finish <--
    
    public ActionResult Create(Auction auction)
    {
    
    // My Edit to the code Start -->
    if(ModelState.IsValid)
    {
    // Only Apply the DateTime if the Action is Valid...
    auction.StartTime = DateTime.Now;
    }
    // My Edit to the code Finish <--
    
    var db = new EbuyDataContext();
    db.Auctions.Add(auction);
    db.SaveChanges();
    return View(auction);
    }
    

    Then Add to the Database the changes in the Package Manager Console -> Add-Migration (Your Change goes here)

    Then run a Database Update in the Package Manager Console -> Update-Database

    Its important to see that the Data that the Database see's is correct in the above implementation:

    E.G: 17/06/2013 12:00:00 AM
    

    This error is an amazingly stupid error but it seems to have caught a lot of people out including my self. Now I know why this error occurs it seems that it is easy to fix and get around but why such a common issue would not be fixed in the last release of MVC is beyond my comprehension.

提交回复
热议问题