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

后端 未结 23 1403
旧时难觅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:49

    The issue is that you're using ApplyPropertyChanges with a model object that has only been populated with data in the form (headline, story, and image). ApplyPropertyChanges applies changes to all properties of the object, including your uninitialized DateTime, which is set to 0001-01-01, which is outside of the range of SQL Server's DATETIME.

    Rather than using ApplyPropertyChanges, I'd suggest retrieving the object being modified, change the specific fields your form edits, then saving the object with those modifications; that way, only changed fields are modified. Alternately, you can place hidden inputs in your page with the other fields populated, but that wouldn't be very friendly with concurrent edits.

    Update:

    Here's an untested sample of just updating some fields of your object (this is assuming you're using LINQ to SQL):

    var story = _db.ArticleSet.First(a => a.storyId == ArticleToEdit.storyId);
    story.headline = ArticleToEdit.headline;
    story.story = ArticleToEdit.story;
    story.image = ArticleToEdit.image;
    story.modifiedDate = DateTime.Now;
    _db.SubmitChanges();
    

提交回复
热议问题