简体   繁体   中英

Manually track changes in Entity DbContext and save changes in to the another DbSet

I present an 'Update' page in my ASP.NET MVC project that enables 'Admin' to update some DbSets with information comes from an Excel file. If the entity exist in the database, I update values; in this case, there is a column mapping algorithm which only updates properties that are mapped with columns from DataTable. If not, I add a new entity to the context.

Before calling SaveChanges() methods, I would like to track changes, such as whether the entry is added or updated, and save them to another DbSet, called Changes. For the 'Updated' scenario, I would like to know which properties are updated including old/new values information.

foreach (var item in db.Items)
{
    var entry = db.Entry(item);
    switch (entry.State)
    {
        case EntityState.Added:
            Debug.Print("Item added: " + item.Name);
            break;
        case EntityState.Modified:
            Debug.Print("Item updated: " + item.Name);
            Debug.Print("Original: " + entry.OriginalValues.PropertyNames);
            Debug.Print("Current: " + entry.CurrentValues.PropertyNames);
            break;
        case EntityState.Unchanged:
            Debug.Print("No changes detected: " + item.Name);
            break;
    }
}

'Update' operation is where I'm stuck. 'entry.OriginalValues.PropertyNames' returns an array ( System.Data.Entity.Internal.ReadOnlySet`1[System.String]) but I am not sure how to get old and new values.

Sorry if this question is a stupid one. Could you give me some advice how to do it or offer another approach?

I think I've found some solution here . If there is better approach, please do not hesitate to contribute.

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