NHibernate query cache not working after update to the database

北城以北 提交于 2019-12-10 23:57:41

问题


I have enabled 2nd level cache in FluentNHibernate:

Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2005
            .ConnectionString(connectionString)
            .Cache(c => c.ProviderClass<SysCacheProvider>().UseQueryCache())
            )
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<PersonMap>());

My mapping is as follows:

    public PersonMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        Cache.ReadWrite();
    }

When I call Persons from my repository, I run:

    var query = session.GetSession().CreateCriteria<Person>("p")
        .Add(Expression.Eq("p.Org.Id", orgRep.GetOrg().Id));
    query.SetCacheable(true);
    return query.List<Person>().AsQueryable<Person>();

When I start the application everything (including cache) works fine. My first query will hit the database, but following ones don't. Problem arises when I save the Person. Person is saved like:

public virtual void Save(Person p)
{
  if (p.Id > 0 && session.GetSession().Get<Person>(p.Id).Org != orgRep.GetOrg())
            throw new SecurityException("Organization mismatch");
  session.GetSession().Merge(p);
  session.GetSession().Flush();
}

Saving works but after that the cache doesn't. Queries will always hit the database. Looking through nhibernate log says that:

 DEBUG - Checking query spaces for up-to-dateness [[Person]]
 DEBUG - Fetching object 'NHibernate-Cache:UpdateTimestampsCache:[Person]@1639794674' from the cache.
 DEBUG - cached query results were not up to date for: sql: SELECT this_.Id as Id0_0_, this_.Name as Name0_0_, this_.Org_id as Org5_0_0_ FROM [Person] this_ WHERE this_.Org_id = ?; parameters: ['1']; first row: 0

What am I doing wrong?


回答1:


Try instantiating an explicit transaction within a session using block. This article looks relevant:- http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactions



来源:https://stackoverflow.com/questions/3626643/nhibernate-query-cache-not-working-after-update-to-the-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!