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

后端 未结 23 1283
旧时难觅i
旧时难觅i 2020-11-28 20:19

I have the following code in my HomeController:

public ActionResult Edit(int id)
{
    var ArticleToEdit = (from m in _db.ArticleSet where m.storyId == id se         


        
相关标签:
23条回答
  • 2020-11-28 20:44

    This problem usually occurs when you are trying to update an entity. For example you have an entity that contains a field called DateCreated which is [Required] and when you insert record, no error is returned but when you want to Update that particular entity, you the get the

    datetime2 conversion out of range error.

    Now here is the solution:

    On your edit view, i.e. edit.cshtml for MVC users all you need to do is add a hidden form field for your DateCreated just below the hidden field for the primary key of the edit data.

    Example:

    @Html.HiddenFor(model => model.DateCreated)
    

    Adding this to your edit view, you'll never have that error I assure you.

    0 讨论(0)
  • 2020-11-28 20:45

    Also, if you don't know part of code where error occured, you can profile "bad" sql execution using sql profiler integrated to mssql.

    Bad datetime param will displayed something like that :

    bad param

    0 讨论(0)
  • 2020-11-28 20:45

    Try making your property nullable.

        public DateTime? Time{ get; set; }
    

    Worked for me.

    0 讨论(0)
  • 2020-11-28 20:46

    It is likely something else, but for the future readers, check your date time format. i had a 14th month

    0 讨论(0)
  • 2020-11-28 20:47

    DATETIME supports 1753/1/1 to "eternity" (9999/12/31), while DATETIME2 support 0001/1/1 through eternity.

    Msdn

    Answer: I suppose you try to save DateTime with '0001/1/1' value. Just set breakpoint and debug it, if so then replace DateTime with null or set normal date.

    0 讨论(0)
  • 2020-11-28 20:47

    You have to enable null value for your date variable :

     public Nullable<DateTime> MyDate{ get; set; }
    
    0 讨论(0)
提交回复
热议问题