I'm at a time with this error and can not find a good solution.
The recording of the objects works normally, however for changes it returns me this message:
Additional information: a different object with the same identifier value was already associated with the session
Class returning to session
public class DataAccesLayer {
private static DataAccesLayer _instance;
public string ConnectionString { get; set; }
private DataAccesLayer() {
}
private ISessionFactory _sessionFactory;
private ISessionFactory SessionFactory {
get {
return _sessionFactory ?? (_sessionFactory = BuildFactory());
}
}
public static DataAccesLayer Instance {
get {
return _instance ?? (_instance = new DataAccesLayer());
}
}
private ISessionFactory BuildFactory() {
try {
IPersistenceConfigurer configDB = PostgreSQLConfiguration
.PostgreSQL82
.ConnectionString(ConnectionString)
.ShowSql()
.FormatSql()
.UseReflectionOptimizer();
FluentConfiguration FConf = Fluently.Configure()
.Database(configDB)
.Mappings(c => c.FluentMappings.AddFromAssemblyOf<System.Retaguarda.Map.UsuarioMap>())
.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true));
return FConf.BuildSessionFactory();
} catch (Exception ex) {
Console.WriteLine("Erro ao carregar configurações do banco de dados\nDica: Verifique as configurações de conexão\n" + ex.Message + "\n" + ex.InnerException);
throw ex;
}
}
public ISession OpenSession() {
return SessionFactory.OpenSession();
}
}
Save Method
ISession session = DataAccesLayer.Instance.OpenSession();
public void Gravar(T entidade) {
using (ITransaction transacao = session.BeginTransaction()) {
try {
session.SaveOrUpdate(entidade);
transacao.Commit();
session.Flush();
} catch (Exception ex) {
if (!transacao.WasCommitted) {
transacao.Rollback();
}
Console.WriteLine("Erro ao gravar:\n" + ex.Message + "\n" + ex.InnerException);
throw ex;
}
}
}
If you use session.Merge(entidade);
it normally writes the changes, but the problem when inserting new items. I thought of a possible solution, but it was kind of strange and I do not intend to use it:
try {
session.SaveOrUpdate(entidade);
} catch (Exception) {
session.Merge(entidade);
}
Another possibility that I tried was to execute a session.Clear();
before SaveOrUpdate
, but when trying to save a "Person" object with "Address" list it returns another error:
Additional information: Illegal attempt to associate with collection with two open sessions