2012-08-08 111 views
2

合併這是我AbstractNHibernateDao,我想使用SaveOrUpdateCopy與合併命令,但是當我試圖用型TI使用有以下錯誤與泛型類型NHibernate的

錯誤1型「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(); 
      } 
     } 

    } 

我怎樣才能使用它T'

+0

@Miroslav後期編輯 – 2012-08-08 09:48:30

回答

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; 
    } 
} 
+1

如果我這樣做,我有以下錯誤錯誤類型「T」必須是引用類型才能使用它作爲泛型類型或方法中的參數'T''NHibernate.ISession.Merge (T)' – 2012-08-08 09:46:58

+2

@Luigi只需添加通用約束到類'where T:class' – 2012-08-08 10:11:35

+0

Ok正常工作:-D – 2012-08-08 10:39:43