似乎直接覆盖 EF 中的 SaveChanges 以添加审核记录器。请参阅下面的 ApplyAuditLogging 方法来设置审计属性(created、createdby、updated、updatedby)。
public override int SaveChanges()
{
var autoDetectChanges = Configuration.AutoDetectChangesEnabled;
try
{
Configuration.AutoDetectChangesEnabled = false;
ChangeTracker.DetectChanges();
var errors = GetValidationErrors().ToList();
if(errors.Any())
{
throw new DbEntityValidationException("Validation errors were found during save: " + errors);
}
foreach (var entry in ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified))
{
ApplyAuditLogging(entry);
}
ChangeTracker.DetectChanges();
Configuration.ValidateOnSaveEnabled = false;
return base.SaveChanges();
}
finally
{
Configuration.AutoDetectChangesEnabled = autoDetectChanges;
}
}
private static void ApplyAuditLogging(DbEntityEntry entityEntry)
{
var logger = entityEntry.Entity as IAuditLogger;
if (logger == null) return;
var currentValue = entityEntry.Cast<IAuditLogger>().Property(p => p.Audit).CurrentValue;
if (currentValue == null) currentValue = new Audit();
currentValue.Updated = DateTime.Now;
currentValue.UpdatedBy = "???????????????????????";
if(entityEntry.State == EntityState.Added)
{
currentValue.Created = DateTime.Now;
currentValue.CreatedBy = "????????????????????????";
}
}
问题是如何让 windows 用户登录/用户名设置对象的 UpdatedBy 和 CreatedBy 属性?因此我不能使用它!
另外,在另一种情况下,我想自动将新的 CallHistory 记录添加到我的联系人中;每当修改联系人时,都需要在子表 CallHistory 中添加一条新记录。所以我在 Repository 的 InsertOrUpdate 中做到了,但感觉很脏,如果我能在更高的级别上做到这一点会很好,因为现在我必须从数据库中设置当前用户。同样这里的问题是我需要从数据库中获取用户以创建 CallHistory 记录(SalesRep = User)。
我的存储库中的代码现在做了 2 件事,1,它在创建或更新对象时创建了一个审计条目,2,它还在更新联系人时创建了一个 CallHistory 条目:
ContactRepository.SetCurrentUser(User).InsertOrUpdate(contact)
为了让用户在存储库上下文中:
var prop = typeof(T).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (prop.GetValue(entity, null).ToString() == "0")
{
// New entity
_context.Set<T>().Add(entity);
var auditLogger = entity as IAuditLogger;
if (auditLogger != null)
auditLogger.Audit = new Audit(true, _principal.Identity.Name);
}
else
{
// Existing entity
_context.Entry(entity).State = EntityState.Modified;
var auditLogger = entity as IAuditLogger;
if (auditLogger != null && auditLogger.Audit != null)
{
(entity as IAuditLogger).Audit.Updated = DateTime.Now;
(entity as IAuditLogger).Audit.UpdatedBy = _principal.Identity.Name;
}
var contact = entity as Contact;
if (_currentUser != null)
contact.CallHistories.Add(new CallHistory
{
CallTime = DateTime.Now,
Contact = contact,
Created = DateTime.Now,
CreatedBy = _currentUser.Logon,
SalesRep = _currentUser
});
}
}
有没有办法以某种方式将 Windows 用户注入 DbContext 中的 SaveChanges 覆盖,还有一种方法可以根据 Windows 登录 ID 从数据库中获取用户,以便我可以在 CallHistory 上设置 SalesRep(参见上面的代码)?
这是我在 MVC 应用程序上对控制器的操作:
[HttpPost]
public ActionResult Create([Bind(Prefix = "Contact")]Contact contact, FormCollection collection)
{
SetupVOs(collection, contact, true);
SetupBuyingProcesses(collection, contact, true);
var result = ContactRepository.Validate(contact);
Validate(result);
if (ModelState.IsValid)
{
ContactRepository.SetCurrentUser(User).InsertOrUpdate(contact);
ContactRepository.Save();
return RedirectToAction("Edit", "Contact", new {id = contact.Id});
}
var viewData = LoadContactControllerCreateViewModel(contact);
SetupPrefixDropdown(viewData, contact);
return View(viewData);
}