Create new DbContextUtils class and move common SaveChanges code to this class. While MasterDbContext has no entities that support IDeletable it does not hurt to check and minimizes duplication
This commit is contained in:
@ -34,54 +34,7 @@ namespace Oqtane.Repository
|
||||
|
||||
public override int SaveChanges()
|
||||
{
|
||||
ChangeTracker.DetectChanges();
|
||||
|
||||
string username = "";
|
||||
if (_accessor.HttpContext != null && _accessor.HttpContext.User.Identity.Name != null)
|
||||
{
|
||||
username = _accessor.HttpContext.User.Identity.Name;
|
||||
}
|
||||
DateTime date = DateTime.UtcNow;
|
||||
|
||||
var created = ChangeTracker.Entries()
|
||||
.Where(x => x.State == EntityState.Added);
|
||||
|
||||
foreach(var item in created)
|
||||
{
|
||||
if (item.Entity is IAuditable)
|
||||
{
|
||||
item.CurrentValues[nameof(IAuditable.CreatedBy)] = username;
|
||||
item.CurrentValues[nameof(IAuditable.CreatedOn)] = date;
|
||||
}
|
||||
}
|
||||
|
||||
var modified = ChangeTracker.Entries()
|
||||
.Where(x => x.State == EntityState.Modified || x.State == EntityState.Added);
|
||||
|
||||
foreach (var item in modified)
|
||||
{
|
||||
if (item.Entity is IAuditable)
|
||||
{
|
||||
item.CurrentValues[nameof(IAuditable.ModifiedBy)] = username;
|
||||
item.CurrentValues[nameof(IAuditable.ModifiedOn)] = date;
|
||||
}
|
||||
|
||||
if (item.Entity is IDeletable && item.State != EntityState.Added)
|
||||
{
|
||||
if ((bool)item.CurrentValues[nameof(IDeletable.IsDeleted)]
|
||||
&& !item.GetDatabaseValues().GetValue<bool>(nameof(IDeletable.IsDeleted)))
|
||||
{
|
||||
item.CurrentValues[nameof(IDeletable.DeletedBy)] = username;
|
||||
item.CurrentValues[nameof(IDeletable.DeletedOn)] = date;
|
||||
}
|
||||
else if (!(bool)item.CurrentValues[nameof(IDeletable.IsDeleted)]
|
||||
&& item.GetDatabaseValues().GetValue<bool>(nameof(IDeletable.IsDeleted)))
|
||||
{
|
||||
item.CurrentValues[nameof(IDeletable.DeletedBy)] = null;
|
||||
item.CurrentValues[nameof(IDeletable.DeletedOn)] = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
DbContextUtils.SaveChanges(this, _accessor);
|
||||
|
||||
return base.SaveChanges();
|
||||
}
|
||||
|
Reference in New Issue
Block a user