How do I Insert or Update (or overwrite) a record using NHibernate?

后端 未结 6 1595
忘掉有多难
忘掉有多难 2021-02-02 00:51

I need to write a row to the database regardless of whether it already exists or not. Before using NHibernate this was done with a stored procedure. The procedure would attempt

6条回答
  •  忘了有多久
    2021-02-02 01:13

    I`m using

        public IList GetByExample(T exampleInstance)
        {
            return _session.CreateCriteria(typeof(T))
                        .Add(Example.Create(exampleInstance))
                        .List();
        }
    
        public void InsertOrUpdate(T target)
        {
            ITransaction transaction = _session.BeginTransaction();
            try
            {
                var res=GetByExample(target);
                if( res!=null && res.Count>0 )
                    _session.SaveOrUpdate(target);
                else
                   _session.Save(target); 
                transaction.Commit();
            }
            catch (Exception)
            {
                transaction.Rollback();
                throw;
            }
            finally
            {
                transaction.Dispose();
            }
        }
    

    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);

提交回复
热议问题