更新到数据库后,NHibernate查询缓存无法正常工作

时间:2010-09-02 11:27:58

标签: nhibernate caching fluent-nhibernate

我在FluentNHibernate中启用了二级缓存:

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

我的映射如下:

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

当我从我的存储库调用人员时,我运行:

    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>();

当我启动应用程序时,所有内容(包括缓存)都能正常运行。我的第一个查询将访问数据库,但后续查询不会。当我保存人员时出现问题。人员保存如下:

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();
}

保存工作但之后缓存不起作用。查询将始终命中数据库。透过nhibernate日志说:

 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

我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试使用块在会话中实例化显式事务。本文看起来很相关: - http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactions

相关问题