c# Nhibernate Session Not updating
I am noticing a weird behavior in my application which is using NHibernate
To give you a bit of background, there are 2 tables in the database:
1) Transaction 2) Vehicle
A transaction has one to one association with vehicle.
I have a database helper class which has Save and GetAll methods in it.
So 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); // This updates the vehicle table's odometer property to 777
}
However, if i modify 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); // This does not update the vehicle table.
// but
dbHelper.Save(t.Vehicle, session); // Works
}
So does that mean that the relationship properties are session dependent ?
edit:
I am using Fluent with AutoMapper and this is one of the convention classed i am using:
internal class OneToOneConvention : IHasOneConvention
{
public void Apply(IOneToOneInstance instance)
{
instance.Cascade.All();
}
}
edit
Here are the 2 methods开发者_Python百科 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>();
}
You are doing it wrong way. When you are retreiving Transaction
object you should make changes inside this NH Session
. Instead of using session that is disposed after using
block, and then you are creating new one. If you need to decouple some logic after you get object from some Session
, then you should pass your Session
instead of creating new one. So workflow in your case should be as follow:
- Open session and retreive
Transaction
object - Make CRUD operations on object (with NHibernate transaction)
- Commit or Rolback transaction
- Close session
The relationship from Transaction to Vehicle is many-to-one not one-to-one. How do you have this mapped?
I agree that this (dbHelper) is not a good pattern for working with NHibernate.
精彩评论