Reputation: 3055
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.
Upvotes: 5
Views: 1643
Reputation: 18977
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();
Upvotes: 2
Reputation: 907
Sure you can. I assume they are already in your model, just add them to the form with Html.HiddenFor(m => m.createdBy)
. Now they are in the form but not displayed, and still have values on Post methods.
Upvotes: 0
Reputation: 5573
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.
Upvotes: 3