I have been trying to connect NHibernate with MySQL for a couple of days. I am using the Repository pattern and it works fine to get data out of the database. However, I can't save data. The code is returning no error, but the data isn't inserted into the database. It all seems like it is rather straightforward, and it does return data. I just can't figure out how to debug the fact that it isn't returning any error when I execute the Nhibernate SaveOrUpdate method, but isn't saving anything.
This is the code that uses the Repository to save the Person object;
[Test]
public void Given_New_User_When_Saved_User_Can_Be_Detected()
{
Person testPerson = new Person("George", "Candle");
IRepository repository = new RepositoryBase();
repository.Save(testPerson);
List<Person> personList = repository.ToList<Person>();
Assert.IsTrue(personList.Exists(x => x.FirstName == "George"));
}
Here is the RepositoryBase code:
public class RepositoryBase: IRepository, IDisposable
{
protected ISession _session = null;
protected ITransaction _transaction = null;
public RepositoryBase()
{
_session = Database.OpenSession();
}
public RepositoryBase(ISession session)
{
_session = session;
}
//Transaction and Session Management Methods
public void BeginTransaction()
{
_transaction = _session.BeginTransaction();
}
public void CommitTransaction()
{
_transaction.Commit();
CloseTransaction();
}
public void RollbackTransaction()
{
_transaction.Rollback();
CloseTransaction();
CloseSession();
}
private void CloseSession()
{
_session.Close();
_session.Dispose();
_session.Flush();
_session = null;
}
private void CloseTransaction()
{
_transaction.Dispose();
_transaction = null;
}
//IRepository members
public virtual void Save(object obj)
{
_session.SaveOrUpdate(obj);
}
}
This is the Database class
public static class Database { private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
string connString = "server=172.16.20.38;Port=3306;userid=root;database=KanbanDevelopment;password=;Persist Security Info=True;";
_sessionFactory = Fluently.Configure()
.Database(MySQLConfiguration.Standard
.ConnectionString(connString))
// .ExposeConfiguration(cfg => new SchemaExport(cfg).Execute(true, true, false))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Person>())
.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}