[英]How to check that which properties/entries are modified and which are not on Editing a record in EF 6
I am developing an MVC 5 application using EF 6. The auto-generated POST method for Edit is: 我正在使用EF 6开发MVC 5应用程序。编辑的自动生成的POST方法是:
public ActionResult Edit([Bind(Include = "Id,Name,Address,Phone,SSNo,D1")] ABC abc)
{
if (ModelState.IsValid)
{
db.Entry(abc).State = EntityState.Modified;
db.SaveChanges();
}
return View(abc);
}
Is there any procedure/method by which I can get that which entries are modified and what were the original values of those entries. 是否有任何过程/方法可以获得哪些条目被修改以及这些条目的原始值是什么。 I have tried the method marked as an answer in this question but it didn't get any changes although changes have been made, ie the loop does not iterates.
我已经尝试过在这个问题中标记为答案的方法,但是虽然已经进行了更改,但是它没有得到任何更改,即循环不会迭代。
My code is: 我的代码是:
public ActionResult Edit([Bind(Include = "Id,Name,Address,Phone,SSNo,D1")] ABC abc)
{
if (ModelState.IsValid)
{
db.ABCs.Attach(abc);
var myObjectState = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager.GetObjectStateEntry(abc);
var modifiedProperties = myObjectState.GetModifiedProperties();
foreach (var propName in modifiedProperties)
{
Console.WriteLine("Property {0} changed from {1} to {2}",
propName,
myObjectState.OriginalValues[propName],
myObjectState.CurrentValues[propName]);
}
Console.ReadKey();
db.Entry(abc).State = EntityState.Modified;
db.SaveChanges();
return Json(abc);
}
return View(abc);
}
ABC model contains many values other than mentioned in method parameters, but I am only passing those which can be edited ABC模型包含除方法参数中提到的以外的许多值,但我只传递可以编辑的值
What I am trying to do is to maintain a log in my database of all the changes made to a document. 我想要做的是在我的数据库中维护对文档所做的所有更改的日志。 I want to include only the changes and the original values before modification in the log not the complete record.
我想在日志中修改之前只包括更改和原始值而不是完整记录。
How can I get this? 我怎么能得到这个?
I implemented this extension method for you: 我为你实现了这个扩展方法:
namespace YourProject.Extensions
{
public static class ModelExtensions
{
public static IEnumerable<KeyValuePair<string, object>> ModifiedValues<T>(this T obj, T modifiedObject)
{
foreach (var property in typeof(T).GetProperties().Where(p => !p.GetGetMethod().IsVirtual))
{
if (property.GetValue(obj).ToString() != property.GetValue(modifiedObject).ToString())
{
yield return new KeyValuePair<string, object>(property.Name, property.GetValue(modifiedObject));
}
}
}
}
}
It's neither the fastest nor the most efficient, but worked in my tests. 它既不是最快也不是最有效的,而是在我的测试中工作。
Use: 使用:
var originalEntity = await db.Entities.AsNoTracking().FirstOrDefaultAsync(e => e.EntityId == modifiedEntity.EntityId);
var modifiedValues = originalEntity.ModifiedValues<MyEntity>(modifiedEntity).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.