【发布时间】:2011-02-11 21:00:40
【问题描述】:
我注意到我使用 NHibernate 的应用程序出现了一个奇怪的行为
给你一些背景知识,数据库中有 2 个表:
1) 交易 2) 车辆
交易与车辆具有一对一的关联。
我有一个数据库助手类,其中包含 Save 和 GetAll 方法。
所以当我运行以下代码时,一切都按预期工作。
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
}
但是,如果我修改我的代码如下
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
}
这是否意味着关系属性取决于会话?
编辑:
我正在使用 Fluent 和 AutoMapper,这是我正在使用的约定之一:
internal class OneToOneConvention : IHasOneConvention
{
public void Apply(IOneToOneInstance instance)
{
instance.Cascade.All();
}
}
编辑
这是 dbHelper 中的 2 个方法
public void Save<T>(T entity, ISession session)
{
using (ITransaction transaction = session.BeginTransaction())
{
try
{
session.SaveOrUpdate(entity);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
和GetAll
public IList<T> GetAll<T>(ISession session) where T : class
{
return session.CreateCriteria<T>().List<T>();
}
【问题讨论】:
-
您能否向我们展示您的映射,我怀疑您的映射上没有 Cascade。
-
我对 dbHelper 深表怀疑 - 你能告诉我们吗?另外:在一堆与数据库会话相关的进程中间有一个定制的 Transaction 类可能不是该类的最佳命名方案。
标签: c# nhibernate session