I posted this question, but there was a guffaw where I overwrote my actual question and just posted code and then it was voted to be closed. I figured the question was pretty much fubared and didn't get its fair shake, so I'm posting it again.
I'm using Entity Framework 4.1. I have a form that has a good number of fields on it. The table itself actually has more fields than what is on the form. I'm trying to find a way to update just the fields that have changed. I found an example of that here:
EntityFramework update partial model
I've revised that to the code below so that I don't have to specify 40+ fields manually. I'm hoping that there's a cleaner way to do this than what is below. Is there?
Warning the code below is a first draft and is rather crude. All suggestions are welcomed. Thanks!
[HttpPost]
public ActionResult Edit(Location location, FormCollection fields)
{
if (ModelState.IsValid)
{
//db is my context
db.Locations.Attach(location);
StringBuilder sb = new StringBuilder();
//Get properties of Location object
PropertyInfo[] pi = typeof(Location).GetProperties();
//loop over keys of fields submitted by the post
foreach (string submittedField in fields.Keys)
{
//If a property name on the Location object matches a field name
//of one of the submitted properties then mark the property as
//modified
if (pi.Any(prop => prop.Name.Equals(submittedField)) &&
!"ID".Equals(submittedField) )
{
db.Entry(location).Property(submittedField).IsModified = true;
sb.AppendLine(submittedField + "Value: " + db.Entry(location).Property(submittedField).CurrentValue );
}
}
LogUtil.WriteCondensed(sb.ToString());
//Save changes to the database
db.SaveChanges();
return RedirectToAction("Index");
}
return View(location);
}