简体   繁体   中英

How to tell which properties have changed on an EF Core Entity?

I have a project where I need to log the "columns" that have changed along with the original value and the changed value. I have an EF Core Entity so I tried doing the following as a test:

var existing = _context.People.FirstOrDefault(p => p.Id == 5);
existing.Lastname += " III";

var changes = new List<Tuple<string,object,object>>();
var proplist = typeof(Person).GetProperties();
foreach(var prop in proplist)
{
   var orig = _context.Entry(existing).OriginalValues[prop.Name];
   var curr = _context.Entry(existing).CurrentValues[prop.Name];
   if(orig != curr){
     changes.Add(new Tuple<string,object,object>(prop.Name,orig,curr));
   }
} 

I expected to simply see "Lastname" show up in my changes. However, I get some weird stuff like Birthdate (DateTime value), Id (int value), etc. The weird part is that the orig value and curr value of these entries are exactly the same -- that is, my entry in the changes table looks like: "Id",2,2 .

Am I doing something wrong or is there a more reliable way to find which properties of an Entity have changed?

You might try this -

var changes = new List<Tuple<string, object, object>>();
var entry = _context.Entry(existing);
foreach (var item in entry.CurrentValues.Properties)
{
    var propEnrty = entry.Property(item.Name);
    if (propEnrty.IsModified)
    {
        changes.Add(new Tuple<string, object, object>(item.Name, propEnrty.OriginalValue, propEnrty.CurrentValue));
    }
}

Edit :
I just ran your code, and found no problem with it. Following is what I got in the changes list -

{(LastName, Cooper, Cooper III)}

But of course I used _context.Entry(existing) hoping that _context.Entity(existing) was a typo while posting and is not really a part of your original code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM