I notice strange behavior in my application that uses NHibernate
To give you a little background, there are two tables in the database:
1) Transaction 2) Car
The deal has a one-to-one connection with the vehicle.
I have a helper database class that has Save and GetAll methods.
Therefore, when I run the following code, everything works as intended.
Transaction t;
using (var session = sessionFactory.OpenSession())
{
t = dbHelper.GetAll<Transaction>(session)[0];
t.Vehicle.Odometer = "777";
dbHelper.Save(t, session);
}
However, if I change my code as follows
Transaction t;
using (var session = sessionFactory.OpenSession())
{
t = dbHelper.GetAll<Transaction>(session)[0];
}
using (var session = sessionFactory.OpenSession())
{
t.Vehicle.Odometer = "777";
dbHelper.Save(t, session);
dbHelper.Save(t.Vehicle, session);
}
Does this mean that relationship properties are session dependent?
change
I use Fluent with AutoMapper, and this is one of the classes that I use:
internal class OneToOneConvention : IHasOneConvention
{
public void Apply(IOneToOneInstance instance)
{
instance.Cascade.All();
}
}
change
Here are two methods inside dbHelper
public void Save<T>(T entity, ISession session)
{
using (ITransaction transaction = session.BeginTransaction())
{
try
{
session.SaveOrUpdate(entity);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
and getall
public IList<T> GetAll<T>(ISession session) where T : class
{
return session.CreateCriteria<T>().List<T>();
}