我发布了这个问题,但是有一个大笑,我覆盖了我的实际问题,只是发布了代码,然后它被投票关闭。我认为这个问题非常令人担忧并且没有得到公平的震动,所以我再次发布它。
我正在使用实体框架 4.1。我有一个表格,上面有很多字段。表格本身实际上比表格上的字段更多。我正在尝试找到一种方法来仅更新已更改的字段。我在这里找到了一个例子:
我已将其修改为下面的代码,这样我就不必手动指定 40 多个字段。我希望有一种比下面更清洁的方法来做到这一点。有没有?
警告下面的代码是初稿,相当粗糙。欢迎所有建议。谢谢!
[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);
}