且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用NHibernate插入或更新(或覆盖)记录?

更新时间:2023-02-06 13:32:44

我使用

    public IList<T> GetByExample<T>(T exampleInstance)
    {
        return _session.CreateCriteria(typeof(T))
                    .Add(Example.Create(exampleInstance))
                    .List<T>();
    }

    public void InsertOrUpdate<T>(T target)
    {
        ITransaction transaction = _session.BeginTransaction();
        try
        {
            var res=GetByExample<T>(target);
            if( res!=null && res.Count>0 )
                _session.SaveOrUpdate(target);
            else
               _session.Save(target); 
            transaction.Commit();
        }
        catch (Exception)
        {
            transaction.Rollback();
            throw;
        }
        finally
        {
            transaction.Dispose();
        }
    }

但是FindByExample方法返回所有类似的对象,而不返回具有确切ID的对象,这是什么建议?因为我只有对象作为参数,所以我无权访问其特定的ID字段,因此无法使用session.get(Object.class(), id);

but FindByExample method returns all objects alike not objects with the exact ID what do you suggest ? since I have only object as parameter I don't have access to its specific ID field so I cannot use session.get(Object.class(), id);