-
Notifications
You must be signed in to change notification settings - Fork 932
Description
I have an issue when I wish to retrieve an entity (which has already been cached) but this time I fetch a lazy loaded property it will trigger a hit to database. For example say I have the following models:
public class Entity {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Component? Component { get; set; }
}
public class Component {
public virtual string Field { get; set; }
}Which are mapped like so:
public class EntityMapping : ClassMapping<Entity> {
public EntityMapping() {
Id(x => x.Id, m => m.Generator(Generators.Identity));
Property(x => x.Name);
Component(x => x.Component, m => {
m.Property(x => x.Field);
m.Lazy(true);
});
Cache(x => x.Usage(CacheUsage.ReadWrite));
}
}Here's my sample application, indicating each time the database is hit:
public static async Task Main() {
using (var sessionFactory = CreateSessionFactory()) {
using (var session = CreateSession(sessionFactory))
using (var transaction = session.BeginTransaction()) {
// Load the entities into the second-level cache.
session.Query<Entity>().WithOptions(o => o.SetCacheable(true)).ToList(); // Hits the database.
var result = session.Query<Entity>().WithOptions(o => o.SetCacheable(true)).Fetch(e => e.Component).FirstOrDefault(); // Hits the database.
var field = result?.Component?.Field;
}
using (var session = CreateSession(sessionFactory))
using (var transaction = session.BeginTransaction()) {
var result = session.Query<Entity>().WithOptions(o => o.SetCacheable(true)).Fetch(e => e.Component).FirstOrDefault();
var field = result?.Component?.Field; // Hits the database.
}
}
}Notice when I try to retrieve an entity via (which has already been cached), the first time it does a fresh hit to the database (to fetch the lazy loaded data as requested) but the cache is not updated. Now any further calls to the lazy loaded data will also trigger a hit to the database since I assume was because it was not included in the original query which cached the entity.
See #3175 for the initial discussion which suggests this is not the intended behaviour.