好的,这里有两种方法。最简单的可能不涉及NHibernate,因为您使用的是SQL Server。。。您可以在表上创建一个INSERT触发器,如下所示:
CREATE TRIGGER tgINSCategory ON Category INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Category (SiteID, Name, SortOrder)
SELECT SiteID, Name,
ISNULL((SELECT MAX(c.SortOrder)
FROM Category c INNER JOIN INSERTED i ON c.SiteID = i.SiteID), 0) + 1
FROM INSERTED
END
在第一个场景中,您只需NHibernate将SortOrder列映射为只读(只需在fluent NHibernate类map SortOrder属性上添加一个.ReadOnly()。
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
public class InsertDefaults : EmptyInterceptor {
private const string CREATED_BY = "CreatedById";
private Hashtable GetInsertLoggablePropertyIndexes(string[] Properties) {
Hashtable result = new Hashtable();
for (int i = 0; i < Properties.Length; i++) {
if (Properties[i] == CREATED_BY) {
result.Add(CREATED_BY, i);
break;
}
}
return result;
}
public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types) {
if (entity is IInsertLoggable) {
Hashtable indexes = GetInsertLoggablePropertyIndexes(propertyNames);
state[(int)indexes[CREATED_BY]] = currentUser;
PropertyInfo createdByProp = entity.GetType().GetProperty(CREATED_BY);
if (createdByProp != null)
createdByProp.SetValue(entity, currentUser, null);
}
return base.OnSave(entity, id, state, propertyNames, types);
}
}
在我看来,这种典型的触发器操作应该存在于数据库中,我会选择第一种方法。。。