开发者

nhibernate many-to-one

I am having this problem..

using (var transaction = Session.BeginTransaction())
            {
                var t = new Ticket();
         开发者_高级运维       t.Title = "TestTicket";
                var ticketId = (Guid)Session.Save(t);

                var pe = new ProcessExec();
                pe.Ticket = t;
                Session.Save(pe);

                var ticket = Session.Get<Ticket>(ticketId);
                transaction.Commit();

                Assert.NotNull(ticket);
                Assert.True(ticket.ProcessExecCollection.Count > 0);
            }

Now the problem is this that the assert fails on

Assert.True(ticket.ProcessExec.Count>0).

But If I do

Session.Refresh(ticket);

just after the transaction.Commit(), everithing works fine. How to tell NHibernate that when I create new ProcessExec and set its ticket, to automatically update the ticket?

I need this because I do lots of stuff creating and selecting in a transaction.

Please help.

<class name="Domain.Model.Sdwwf.ProcessExec" table="[PROCESS_EXEC]" schema="[SDWWF]" dynamic-update="true">
<id name="Id" column="ID" type="Guid">
  <generator class="guid" />
</id>
<version name="Version" column="VERSION" />
<many-to-one name="Ticket" column="[TICKET_ID]" cascade="save-update, persist" />  

<class name="Domain.Model.Sdwwf.Ticket" table="[TICKET]" schema="[SDWWF]" dynamic-update="true">
    <id name="Id" column="ID" type="Guid">
      <generator class="guid" />
    </id>
    <version name="Version" column="VERSION" />
    <bag name="ProcessExec" inverse="true" cascade="all">
      <key column="[TICKET_ID]" />
      <one-to-many class="Softworks.SDW.Domain.Model.Sdwwf.ProcessExec" />
    </bag>
    <property name="Title" column="[TITLE]" />
</class>


What's happening is that when you do the ISession.Get call before you commit the transaction, the session has not been flushed yet, so it gets the cached version of the entity. NHibernate is not like using a database connection as it is very lazy most of the time. It will only go to the database when it absolutely has to.

You can either manually refresh the entity, just like you said or you can manually do

ticket.ProcessExecCollection.Add(new ProcessExec());

Then when you save the ticket, NHibernate will cascade the newly created ProcessExec. Thereby saving you a second call to NHibernate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜