My table has two columns CreatedBy
and CreateTime
. In my view form, I don't have these fields. Now when I update a record using ASP.NET MVC4 Edit (post) method, these columns are set to null. But I want to retain the values. I know in my Edit (post) method, I can retrieve the record from the database and set these manually. But I am wondering whether I can ask Entity Framework not to change the values of these fields.
No you can't, if you want to keep the old values then you have to get the record first and then manually assign the values that you want to update. The only other way is to go through your entity property by property and tag which ones you want to modify, like so:
db.MyEntity.Attach(myEntity);
db.Entry(myEntity).Property(e => e.MyProperty).IsModified = true;
db.SaveChanges();
either way you end up having to do the manual work yourself.
You have to choices here:
1) As @KennyZ mentioned, add to @Html.HiddenFor()
somewhere in your view, into your form:
@Html.HiddenFor(m => m.CreatedBy)
@Html.HiddenFor(m => m.createTime)
2) You can manually update that entity and leave those two properties alone:
var ent = dbctx.Entities.Find(model.ID);
ent.Prop1 = model.Prop1;
// ... also for other properties except those two property
dbctx.SaveChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With