-插入数据 INSERT INTO Parent (Id) VALUES (p0);p0 1 INSERT INTO RelationsTable (ParentID, KeyId, Value) VALUES (p0, p1, p2);p0 1, p1 0, p2 0 INSERT INTO RelationsTable (ParentID, KeyId, Value) VALUES (p0, p1, p2);p0 1, p1 1, p2 1 --ISession.Get()方法 SELECT parent0_.Id as Id0_0_ FROM Parent parent0_ WHERE parent0_.Idp0;p0 1 --ISession.SaveOrUpdateCopy()方法 SELECT parent0_.Id as Id0_0_, relations1_.ParentID as ParentID2_, relations1_.Value as Value2_, relations1_.KeyId as KeyId2_ FROM Parent parent0_ left outer join RelationsTable relations1_ on parent0_.Idrelations1_.ParentID WHERE parent0_.Idp0;p0 1分析在NHibernate API文档中对ISession.SaveOrUpdateCopy()方法这样的解释NameDescriptionSaveOrUpdateCopy(Object)Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved or does not exist in the database, save it and return it as a newly persistent instance. Otherwise, the given instance does not become associated with the session.SaveOrUpdateCopy(Object, Object)Copy the state of the given object onto the persistent object with the given identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If there is no database row with the given identifier, save the given instance and return it as a newly persistent instance. Otherwise, the given instance does not become associated with the session.简单的就是说将传入的对象的状态也就是属性赋给Session缓存中相同键值的对象上如果该对象不存在则从数据库加载传入的对象并不进行持久化。如果数据库不存在这个对象则进行保存。所以当我们调用ISession.SaveOrUpdateCopy()方法时先把传的对象赋值到新的对象(如果传的参数为空则抛出“attempt to create merge event with null entity”异常)然后发出一条SQL查询数据库数据库里有这个对象并相同什么都不做。数据库里有这个对象其属性改变了就发送SQL更新数据库数据库没有这个对象则保存这个对象到数据库。我想这样做的目的就是保证对象的原子性不可能别人已经动过数据库了你还拿一个脏对象来操作。大家可以修改上面的代码测试一下。那么ISession.SaveOrUpdateCopy()方法在哪里使用呢