与泛型Nhibernate合并

时间:2012-08-08 09:37:44

标签: c# nhibernate generics types

这是我的AbstractNHibernateDao,我想将SaveOrUpdateCopy与Merge命令一起使用,但是当我尝试使用Type T时,我有以下错误

  

错误1类型'T'必须是引用类型才能将其用作   泛型类型或方法中的参数'T'   'NHibernate.ISession.Merge(T)'

public abstract class AbstractNHibernateDao<T, TIdT> : IDao<T, TIdT>
    {
        private readonly Type _persitentType = typeof (T);

        /// <summary>
        ///   Exposes the ISession used within the DAO.
        /// </summary>
        private static ISession NHibernateSession
        {
            get { return NHibernateSessionManager.Instance.GetSession(); }
        }

        #region IDao<T,TIdT> Members



        /// <summary>
        ///   For entities that have assigned ID's, you must explicitly call Save to add a new one. See http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-id-assigned.
        /// </summary>
        public T Save(T entity)
        {
            NHibernateSession.Save(entity);
            NHibernateSession.Flush();
            return entity;
        }

        /// <summary>
        ///   For entities with automatatically generated IDs, such as identity, SaveOrUpdate may be called when saving a new entity. SaveOrUpdate can also be called to update any entity, even if its ID is assigned.
        /// </summary>
        public T SaveOrUpdate(T entity)
        {
            NHibernateSession.SaveOrUpdate(entity);
            NHibernateSession.Flush();
            return entity;
        }

        public T SaveOrUpdateCopy(T entity)
        {
            NHibernateSession.Merge(entity);
            return entity;
        } 

        public void Delete(T entity)
        {
            NHibernateSession.Delete(entity);
            NHibernateSession.Flush();
        }

        /// <summary>
        ///   Commits changes regardless of whether there's an open transaction or not
        /// </summary>
        public void CommitChanges()
        {
            if (NHibernateSessionManager.Instance.HasOpenTransaction())
            {
                NHibernateSessionManager.Instance.CommitTransaction();
            }
            else
            {
                // If there's no transaction, just flush the changes
                NHibernateSessionManager.Instance.GetSession().Flush();
            }
        }

    }

我怎么能用它?

1 个答案:

答案 0 :(得分:3)

您应该Merge(entity)代替Merge(T)

public abstract class AbstractNHibernateDao<T, TIdT> 
    : IDao<T, TIdT> where T : class
{
    public T SaveOrUpdateCopy(T entity)
    {
        NHibernateSession.Merge(entity);
        return entity;
    }
}