J'ai le code ci-dessous. Il donne parfois l'erreur d'exécution:Utiliser Merge au lieu de SaveOrUpdate
a different object with the same identifier value was already associated with the session
je vis une solution qui suggère d'utiliser Merge
au lieu de SaveOrUpdate
. En essayant cela (voir la ligne commentée). Je reçois une erreur de compilation:
The type T must be a reference type in order to use it as a parameter
T
in the generic type or method
La solution à cette erreur dit d'ajouter T : class
à la déclaration de classe. Il a déjà T : new()
. Quand je le change en "classe" j'obtiens d'autres erreurs de compilation.
'T' must be an abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method
et aussi voir GetDefaultInstance()
Comment puis-je faire?
public class GenericNHibernateDataService<T, ID> : Interface.Data.IGenericDataService<T, ID> where T : new()
public virtual T GetDefaultInstance()
{
return new T(); // compile error when changing to T : class
// Cannot create an instance of the variable type 'T' because it does not have the new constraint
}
public virtual T SaveOrUpdate (T entity)
{
NHibernate.ITransaction tx = null;
try
{
tx = this.Session.BeginTransaction();
this.Session.SaveOrUpdate (entity);
//Session.Merge(entity); //The type T must be a reference type in order to use it as a parameter `T` in the generic type or method
tx.Commit();
}
catch (System.Exception ex)
{
tx.Rollback();
throw ex;
}
return entity;
}
...
}
Avez-vous essayé d'ajouter les contraintes: 'où T: classe, nouvelle()'? –
Ça marche! Postez cela comme réponse si vous le souhaitez. –
Terminé. Content que ça a marché. –