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

后端 未结 6 1530
忘掉有多难
忘掉有多难 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:11

    call hibernate.saveOrUpdate() which will check if the object is in the database, update it if it is, and save (i.e. insert) it if it is not.

    0 讨论(0)
  • 2021-02-02 01:13

    I`m using

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

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

    0 讨论(0)
  • 2021-02-02 01:23

    Use the session.SaveOrUpdate(object) method.

    0 讨论(0)
  • 2021-02-02 01:27

    Query objects where keyword = x, take FirstOrDefault. If it's null, Add new object, if it exists, update object that you got and call saveOrUpdate on it.

    0 讨论(0)
  • 2021-02-02 01:33

    Typically, NHibernate can rely on the unsaved-value to determine whether it should insert or create the entity. However, since you are assigning the ID, to NHibernate it looks like your entity has already been persisted. Therefore, you need to rely on versioning your object to let NHibernate know that it is a new object. See the following link for how to version your entity:

    http://web.archive.org/web/20090831032934/http://devlicio.us/blogs/mike_nichols/archive/2008/07/29/when-flushing-goes-bad-assigned-ids-in-nhibernate.aspx

    0 讨论(0)
  • 2021-02-02 01:33

    You can do

    Obj j = session.get(Object.class(), id);
    if (j != null)
       session.merge(myObj);
    else
       session.saveOrUpdate(myObj);
    
    0 讨论(0)
提交回复
热议问题