Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

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

I have an ASP.NET MVC application where I am editing an existing database to update a paticular field, DateTime. My database has 4 fields, two of which are DateCreated and DateModified. When I try to update the field, I want to keep DateCreated time the same, no reason to update the date it was created, and I change the DateModified time to the current time using DateTime.Now

Here is the given code just in-case I am doing something wrong. This is my first time using ASP.NET MVC so go gentle. I have seen other answers where Context is called, but I can't find any reference to it. When I run the application I receive the error message in the title and the contractEntity.SaveChanges() is in red.

public ActionResult Edit(Contract editContract) {
var contract = (from c in contractEntity.Contracts where c.Id == editContract.Id select c).First();
if (!ModelState.IsValid)
    return View(contract);
// editContract.DateCreated = contract.DateCreated;
// editContract.DateModified = DateTime.Now;
  contractEntity.ApplyCurrentValues(contract.EntityKey.EntitySetName, editContract);
  contractEntity.SaveChanges();
  return RedirectToAction("Index");
}

Please, any help is appreciated. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For me, I had the same issue, but the problem was that by default when I saved my Model, an invalid DateTime was being created. I had a field CreatedOn and had not set it to anything, which meant the value was 01/01/0001 which was an invalid DateTime for SQL. Setting it got rid of the problem for me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...