Update object using entity structure ignoring some properties
I am working with asp.net mvc 4. I need to update persistence store using edit method, but I want to ignore some columns.
I found several answers here, but they didn't work for me (I suppose).
Here's my method:
[HttpPost]
public ActionResult Edit(Candidat candidat)
{
ProcRecDB _db = new ProcRecDB(); // from DbContext
if (ModelState.IsValid)
{
_db.Entry(candidat).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(candidat);
}
The candidate model has 10 properties; how would i ignore some of them?
source to share
You can create a new object, attach it to the db context, and then update only the properties you want to keep.
[HttpPost]
public ActionResult Edit(Candidat candidat)
{
ProcRecDB _db = new ProcRecDB(); // from DbContext
if (ModelState.IsValid)
{
var updatedCandidat = new Candidat { Id = candidat.Id };
_db.Attach(updatedCandidat);
// Set the properties that you would like to update. This must be
// done after the object has been attached to the db context.
updatedCandidat.FirstName = candidat.FirstName;
updatedCandidat.LastName = candidat.LastName;
...
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(candidat);
}
source to share
You are in the same position as me. I have similar things.
You have options:
You can use NotMapped (if you don't want to store any value).
However, I think you want this:
if it's read-only and you don't want to change it, you can do something like this:
var attachedEntity = this.context.Entry(orignalEntity);
attachedEntity.CurrentValues.SetValues(updatedEntity);
List<string> excludeProperties = new List<string>();
// Some of these fields you cannot just modify at all.
excludeProperties.Add("UniqueIdentifier");
excludeProperties.Add("AuthorID");
excludeProperties.Add("DateCreated");
// You could even ask your dervived calls to tell which one to exclude
// excludeProperties.AddRange(this.ExcludeUpdateProperties());
foreach (var name in excludeProperties)
{
var property = attachedEntity.Property(name);
if (property != null)
{
attachedEntity.Property(name).IsModified = false;
}
}
with this approach, instead of updating those fields that need to be updated, you can use attachEntity.CurrentValues.SetValues (updatedEntity) which will set the whole value to be a new value and then you can exclude it. This approach is better than updating each field one at a time.
source to share