Reputation: 91786
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.
Upvotes: 22
Views: 38876
Reputation: 1791
You can also edit the model (or in EF in the .edmx) and set the StoreGeneratedPattern
to Computed for the field in question. That will cause it not to save that to that field, because it gets calculated by the SQL server.
Upvotes: 11
Reputation: 9485
Just use a DateTime nullable such DateTime? in your domain entity property if your column in your database can be nullable. This will make it work.
Upvotes: 3
Reputation: 183
I have the same error and i discovered that if you have a SQL 2008 DB with a DateTime Nullable field, DON'T explicit assign Null (Nothing) to the field in your code, this will cause this error, or you can change all DateTime fields to DateTime2.
Upvotes: 7
Reputation: 654
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.
Upvotes: 38
Reputation: 91786
After reading this website I found to open the .edmx file for my database and change:
<...Provider="System.Data.SqlClient" ProviderManifestToken="2008".../>
to
<...Provider="System.Data.SqlClient" ProviderManifestToken="2005".../>
Is this acceptable or is there a better approach to fixing that error?
Upvotes: 19