Mar*_*son 7 .net nhibernate lifecycle
我认为我在概念上缺少关于NHibernate的东西.我有一个Instrument对象映射到instruments我的数据库中的表.我还有一个BrokerInstrument对象映射到brokerInstruments我的数据库中的表.brokerInstrumnets是一张儿童桌instruments.我的课程看起来像:
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; }
}
Run Code Online (Sandbox Code Playgroud)
在我的单元测试中,如果我Instrument从数据库中检索一个然后将其删除,则会将其与ISession.Delete子项一起从数据库中删除(我已在我的映射文件中启用了cascade-all).该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
}
Run Code Online (Sandbox Code Playgroud)
关于内存中对象的最佳实践是什么?我现在处于不一致状态,因为我Instrument在内存中有一个数据库中不存在的对象.我是一名新手程序员,因此非常感谢链接的详细解答.
一些东西。您的 _session 实际上是您的工作单元。您在这里所做的所有工作都是删除仪器 i。也许将该代码包装在 using(_session) 中。
当你做你的断言时。创建一个新会话来执行检索检查。
至于“i”对象 - 首先 - 不要将其命名为 i,因为它应该仅用于循环计数器。其次,在此断言中,Assert.That(i.BrokerInstruments.Count, Is.EqualTo(0))i.BrokerInstruments 的计数不一定会更改,除非您的 IInstrumentRepo.Delete(Instrument someInstrument) 实现显式将 someInstrument 设置为 null。
希望这个对你有帮助。