views:

83

answers:

0

Hi, I'm having a problem with the first level cache in NHibernate in our web application.

In our application we have a context based session that is alive during each request (opened on request start and closed on request end).

In addition to this we have a model structure with User, Organization and OrganizationType such that each User has an Organization and each Organization has an OrganizationType.

When I create a critera on our session to get all User objects and their Organization objects I use the following code:

public IList<User> GetAllUsers()
{
    var session = DependencyManager.Resolve<ISession>(); //this gets our current session through dependency injection

    using (var scope = new NhTransactionScope())
    {
        var criteria = session.CreateCriteria(typeof(User))
            .AddOrder(Order.Asc("FirstName"))
            .AddOrder(Order.Asc("LastName"))
            .SetFetchMode("Organization", FetchMode.Join)

        IList<User> users = criteria.List<User>();

        scope.Complete();
        return users;
    }
}

This works perfectly for what I want.

Part of the problem is that all Organization objects get their OrganizationType set as a proxy object (since I don't join with that table) and all these proxy objects are saved to the first level cache. This would normally not be a problem if not for the fact that later on in the same request, and thus the same session, I want to fetch all Organization objects and their OrganizationType objects.

This is done through a similar function:

public IList<Organization> GetAllOrganizations()
{
    IList<Organization> organizations;

    using (var scope = new NhTransactionScope())
    {
        var criteria = session.CreateCriteria(typeof(Organization))
            .AddOrder(Order.Asc("Name"))
            .SetFetchMode("OrganizationType", FetchMode.Join)

        organizations = criteria.List<Organization>();

        scope.Complete();
        return organizations;
    }
}

Now to the big problem. Because my first selection put all OrganizationType proxy objects in the first level cache, when I do my second selection, even though I can see that all OrganizationType data gets fetched in the SQL select statement, NHibernate decides to use the OrganizationType proxy objects from the first level cache to populate my collection.(!!!)

Does anyone know how I can make sure that NHibernate uses the latest selected data or that it properly updates the first level cache?

Otherwise I have a number of extra SQL statements firing when I read from the collection (or in our case it doesn't work at all because we serialize the collection to JSON and the .Net JavascriptSerializer can't figure out what to do with the proxy objects).