审核基类中的信息
本文关键字:信息 基类 | 更新日期: 2023-09-27 18:29:14
我正在使用NHIBERNATE创建一个ASP.NET MVC3应用程序。我有一个基类Entity,用于捕获一些审核信息,如CreatedBy、CreatedOn、UpdatedBy、UpdatedOn等。每当创建并持久化/更新派生类时,这些属性都应该自动填充。
由于实体类型和所有其他类型都在域程序集中定义,将用户信息从Web项目渗透到DOMAIN以在Entity基类中填充信息的最佳方式是什么
编辑
此外,
- 目前,我将所有属性定义为公共虚拟,那么我如何实现它们,以便在持久化时动态创建日期/userId
- 我希望基类属性在派生的具体类的每个表中保持不变(每个具体类的表)。如何使用FLUENT NHIBERNATE指定它(我没有使用自动映射)
打开会话时使用拦截器:
sessionFactory.OpenSession(new AuditInterceptor());
文件:AuditInterceptor.cs
using System;
using NHibernate;
using NHibernate.Type;
using System.Threading;
using System.Security;
namespace bla
{
/// <summary>
/// NHibernate Interceptor that stores audit information (idlogin and datetime.now) on every save and update
/// </summary>
public class AuditInterceptor : EmptyInterceptor
{
private int updates;
private int creates;
private int loads;
private ISession session;
public override void OnDelete(object entity,
object id,
object[] state,
string[] propertyNames,
IType[] types)
{
// do nothing
}
public override bool OnFlushDirty(object obj, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types)
{
bool found = false;
if (obj is Entity)
{
updates++;
for (int i = 0; i < propertyNames.Length; i++)
{
if ("dtlastchanged".Equals(propertyNames[i].ToLower()))
{
currentState[i] = DateTime.Now;
found = true;
}
if ("lastchangedby".Equals(propertyNames[i].ToLower()))
{
currentState[i] = this.session.Get<Login>(IdLogin, LockMode.None);
found = true;
}
}
}
return found;
}
public override bool OnLoad(object obj, object id, object[] state, string[] propertyNames, IType[] types)
{
if (obj is Entity)
{
loads++;
}
return false;
}
public override bool OnSave(object entity,
object id,
object[] state,
string[] propertyNames,
IType[] types)
{
bool found = false;
if (entity is Entity)
{
creates++;
for (int i = 0; i < propertyNames.Length; i++)
{
if ("dtlastchanged".Equals(propertyNames[i].ToLower()))
{
state[i] = DateTime.Now;
found = true;
}
if ("lastchangedby".Equals(propertyNames[i].ToLower()) && !(entity is Login && (entity as Login).IsInVerification))
{
state[i] = this.session.Get<Login>(IdLogin, LockMode.None);
found = true;
}
}
}
return found;
}
public override void AfterTransactionCompletion(ITransaction tx)
{
//if (tx.WasCommitted)
//{
// System.Console.WriteLine("Creations: " + creates + ", Updates: " + updates, "Loads: " + loads);
//}
updates = 0;
creates = 0;
loads = 0;
}
public override void SetSession(ISession session)
{
this.session = session;
base.SetSession(session);
}
protected long IdLogin
{
get
{
return (Thread.CurrentPrincipal.Identity as CustomIdentity).IdLogin; // or something else that holds the id of the current logged in user
}
}
}
}