如何通过一次调用Save来更新行并在NHibernate中自动插入一行?

时间:2010-03-10 23:56:57

标签: c# nhibernate versioning

假设我有一个Type II SCD数据库,基本上只附加。我正在使用NHibernate将对象持久化到我的数据库。我有一个像这样的对象:

Pony
|- int Id
|- Guid EntityId
|- string PonyName
|- string PonyColor
|- int RevisionValidFrom
|- int RevisionValidTo

这是一个典型的场景:

Pony myLittlePony = myStable.GetLatestPonyByGuid("0f1ac08a-3328-43db-b278-77c272e4fea3");
myLittlePony.PonyColor = "Fish";
myNHSession.Save(myLittlePony);

我希望能够调用Session.Save(myLittlePony)并让NHibernate将旧实体的RevisionValidTo更新为我指定的任何内容,然后将修改后的Pony作为新行插入新Id {{1}} 1}},基本上好像是一个全新的对象被持久化到数据库。

2 个答案:

答案 0 :(得分:0)

可以使用custom SQL for update完成此操作。

答案 1 :(得分:0)

我最终创建了自己的SaveOrUpdateEventListener并将其注册到NHibernate的配置中。然后我发出一个原始的SQL命令。

对于NHibernate配置:

var listener = new PonySaveOrUpdateEventListener();
config.SetListener(NHibernate.Event.ListenerType.SaveUpdate, listener);
config.SetListener(NHibernate.Event.ListenerType.Save, listener);

班级:

public class PonySaveOrUpdateEventListener : DefaultSaveOrUpdateEventListener
{
    protected override object EntityIsPersistent(SaveOrUpdateEvent @event)
    {
        Pony ent = @event.Entity as Pony;

        // I don't care if it's not a pony or if the entity doesn't need updating, call base!
        if (ent == null || !IsDirty(@event))
            return base.EntityIsPersistent(@event);

        // Do nasty dialect-specific raw SQL because using NH to update this row throws us into an infinite loop
        string tablename = ((ILockable)@event.Entry.Persister).RootTableName.ToLower();
        System.Data.IDbCommand command = ((ISession)@event.Session).Connection.CreateCommand();
        command.CommandText = String.Format("update {0} set RevisionValidTo = {1} where Id = '{2}'", tablename, CurrentRevision.Id, ent.Id);
        command.ExecuteNonQuery();

        // Make the event look like it was never persistent and force a transient insert of the entity
        ent.Id = Guid.Empty;
        @event.Entry = null;
        return EntityIsTransient(@event);
    }

    protected override object EntityIsTransient(SaveOrUpdateEvent @event)
    {
        Pony ent = @event.Entity as Pony;
        if (ent == null)
            return base.EntityIsTransient(@event);

        ent.RevisionValidFrom = Host.NextRevision;
        ent.RevisionValidTo = null;

        return base.EntityIsTransient(@event);
    }

    private static bool IsDirty(SaveOrUpdateEvent @event)
    {
        IEntityPersister persister = @event.Entry.Persister;
        object[] oldState = @event.Entry.LoadedState;
        object[] currentState = persister.GetPropertyValues(@event.Entity, @event.Session.EntityMode);
        Int32[] dirtyProps = persister.FindDirty(currentState, oldState, @event.Entity, @event.Session);
        return dirtyProps != null;
    }
}