views:

368

answers:

3

I have written an integrationtest that fails:

    [Test]
    public void Find_WorkItemWithMatchingDescriptionExistsInRepository_ReturnsWorkItem()
    {
        // arrange
        WorkItemRepository repository = new WorkItemRepository(IsolatingFactory);

        const string Description = "A";
        WorkItem itemWithMatchingDescription = WorkItem.Create(1, Description);
        repository.Commit(itemWithMatchingDescription);

        // act
        List<WorkItem> searchResult = repository.Find(Description);

        // assert
        CollectionAssert.Contains(searchResult, itemWithMatchingDescription);
    }

When watching the sql output from nhibernate i notice that it creates a select-statement for the repository.Find() operation, but no insert operation before the select. If i put an explicit session.Flush() after the repository.Commit it works as expected, but I find this behaviour odd. Why doesn't nhibernate flush the session automatically when there are pending insert and a query is performed against the session?

I found this in the documentation:

9.6. Flush

From time to time the ISession will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points

* from some invocations of Find() or Enumerable()
* from NHibernate.ITransaction.Commit()
* from ISession.Flush() 

It looks as the default nhibernate behaviour is to flush before quering by find. My repository uses Ling to nhibernate for the query specification, maybe this is a bug.

Update

If I change my mapping from:

    public WorkItemClassMap()
    {
        Not.LazyLoad();

        Id(wi => wi.Id).GeneratedBy.Assigned();
        Map(wi => wi.Description).Length(500);
        Version(wi => wi.LastChanged).UnsavedValue(new DateTime().ToString());
    }

To:

    public WorkItemClassMap()
    {
        Not.LazyLoad();

        Id(wi => wi.Id).GeneratedBy.Identity();
        Map(wi => wi.Description).Length(500);
    }

It works as expected (nhibernate flushes the insert to the database before performing the query). I can't see any good reason for this behavior so I'm assuming its a bug. Looks like a need to do manual flush before querying in my repositories, which is not something I really want to do.

+2  A: 

You should use different ISession instances for the insert and select methods. It's best if these sessions are in a using block so that they are properly disposed of and inside a database transaction:

using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
    // perform your insert here
    tx.Commit();
}
Darin Dimitrov
Yeah like that :)
Mark Dickinson
I don't like this constraint. It should be perfectly acceptable to create a transaction and perform both read and writes inside the same transaction.
Marius
It is acceptable. The important thing is to create and commit the `ITransaction` for each unit of work. You should be doing this anyway and as the documentation says, it automatically causes a flush.
Aaronaught
Hmm, this is giving me a headache. I just refactored my code so that transactions are started explictly and commited for each unit of work. Now, if there already exists a unit of work when I create a new one (which means that the unit of works will share the same session, but both will invoke session.BeginTransaction(), I get an error if the outer unit of work tries to RollBack when the inner unit of work has completed the transaction (although both have requested their own transaction).
Marius
A: 

Assuming that your repository wither creates or takes a session that already exists. When you make the WorkItem, and commit it, it just goes on a list of jobs for that session to do. If your repository does not create a transaction and your commit method does not explicity commit the transaction. Then the update or save will wait until the session closes, so although you can see the object that you created, you will not be able to get the scope identity, for instance, until you close the session or flush it. Certainly searchResult won't know anything about the object you created without a flush or closing transaction.

There are perils with transactions the same as sessions in general but if you are making new objects you should be using explicit transactions. NHProfiler will readily warn you about this.

Mark Dickinson
I use explicit transactions, the whole integration test runs in a single session/transaction. I still don't see a good reason as to why nhibernate does not autoflush when seing that i'm performing a query.
Marius
Yeah, I'm not saying its ideal, I found out about it yesterday, when I had a child object that I had just added (and called session.update on the parent object) and yet the object's id had not been set. It seemed strange but like I said, NHProfiler will warn you about this. I opted to have my repository interface expose methods to begin and commit transactions on a current session, this way i am in theory not tied to nhibernate. Cheers, Mark
Mark Dickinson
+2  A: 

Is WorkItem in your example mapped with a composite ID? I just coded a simple test. My dummy class would auto flush when I had a single identity column. I wrote the same test though with a composite ID and I get the behavior you describe above.

James Bigler
You are definitely on to something here. I don't use composite keys, but the primary key was assigned and I also use a Version field. If i removed the version field and also changed to primary key to for ex "Generated by Identity" it works as expected, this must be a bug.
Marius