我想我在概念上對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
對象,它在數據庫中不存在。我是一個新手程序員,所以我們非常感謝帶有鏈接的詳細答案。