bilal-fazlani / tracker-enabled-dbcontext

Tracker-enabled DbContext offers you to implement full auditing in your database
https://tracker-enabled-dbcontext.bilal-fazlani.com/
Other
217 stars 110 forks source link

AuditLogs inserted after SaveChanges fail + Reload #186

Open bergerb-com opened 1 year ago

bergerb-com commented 1 year ago

When SaveChanges fails (eg. no permission to save Detail-Table), then the Detail-Entity is reloaded (Changes reverted), AuditLogs will be inserted at the next SaveChanges.

Is there a useful workaround for that usecase? I could try to remove all pending AuditLogs associated with that Detail-Entity, but I feel like that would be the job of the TrackerContext :)

var master = dbcontext.Masters.FirstOrDefault();
var detail = master.Detail.FirstOrDefault();

detail.TextColumn = "This ist a Test change, that should not show up!";

try
{
    dbcontext.SaveChanges();
}
catch (DbUpdateException ex)
{
    SqlException innerException = ex.InnerException?.InnerException as SqlException;

    if (innerException != null && (innerException.Number == 229 || innerException.Number == 230))
    {
        // Show MessageBox: No Permission

        // User closes Edit-Dialog, does not save Detail-Entity, Detail-Entity gets refreshed
        // (I know, this is not the right place to put that code, but it illustrates what the user could do)
        dbcontext.Entry(detail).Reload();

        // User SavesChanges
        dbcontext.SaveChanges();
    }
    else
        throw ex;
}
AuditLogId UserName EventDateUTC EventType TypeFullName RecordId PropertyName OriginalValue NewValue
1 NULL 2023-02-06 12:33:30.723 0 Test_redundant.Master 1 MasterId NULL 1
2 NULL 2023-02-06 12:33:30.733 0 Test_redundant.Detail 1 DetailId NULL 1
2 NULL 2023-02-06 12:33:30.733 0 Test_redundant.Detail 1 Master_MasterId NULL 1
3 NULL 2023-02-06 12:44:20.713 2 Test_redundant.Detail 1 TextColumn NULL This ist a Test change, that should not show up! should not show up!
bilal-fazlani commented 1 year ago

Valid point. Unfortunately, I am not actively developing this project anymore. But PRs are welcome!