我想我在概念上对NHibernate缺少一些东西。我有一个Instrument
对象,它映射到我的数据库中的instruments
表。我也有一个BrokerInstrument
对象,它映射到我的数据库中的我的brokerInstruments
表。 brokerInstrumnets
是instruments
的子表。我班的样子:NHibernate中的对象生命周期
public class Instrument : Entity
{
public virtual string Name { get; set; }
public virtual string Symbol {get; set;}
public virtual ISet<BrokerInstrument> BrokerInstruments { get; set; }
public virtual bool IsActive { get; set; }
}
public class BrokerInstrument : Entity
{
public virtual Broker Broker { get; set; }
public virtual Instrument Instrument { get; set; }
public virtual decimal MinIncrement { get; set; }
}
在我的单元测试,如果我从数据库中检索的Instrument
,然后用ISession.Delete
删除它,它是从数据库中与孩子们一起删除(我有级联全部开启在我的映射文件中)。然而Instrument
仍然存在于内存中。例如:
[Test]
public void CascadeTest()
{
int instrumentId = 1;
IInstrumentRepo instruments = DAL.RepoFactory.CreateInstrumentRepo(_session);
Instrument i = instruments.GetById<Instrument>(instrumentId); // retrieve an instrument from the db
foreach (BrokerInstrument bi in i.BrokerInstruments)
{
Debug.Print(bi.MinIncrement.ToString()); // make sure we can see the children
}
instruments.Delete<Instrument>(i); // physically delete the instrument row, and children from the db
IBrokerInstrumentRepo brokerInstruments = DAL.RepoFactory.CreateBrokerInstrumentRepo(_session);
BrokerInstrument deletedBrokerInstrument = brokerInstruments.GetById<BrokerInstrument>(1); // try and retrieve a deleted child
Assert.That(instruments.Count<Instrument>(), Is.EqualTo(0)); // pass (a count in the db = 0)
Assert.That(brokerInstruments.Count<BrokerInstrument>(), Is.EqualTo(0)); // pass (a count of children in the db = 0)
Assert.That(i.BrokerInstruments.Count, Is.EqualTo(0)); // fail because we still have the i object in memory, although it is gone from the db
}
关于内存中对象的最佳做法是什么?我现在处于不一致的状态,因为我在内存中有一个Instrument
对象,它在数据库中不存在。我是一个新手程序员,所以我们非常感谢带有链接的详细答案。