Cached Fetch for User Roles from NHibernate in an MVC App

116 views Asked by At

Using classes like this...

public class Login
{
    public virtual Guid LoginId { get; set; }
    public virtual string Name { get; set; }
    public virtual string Email { get; set; }
    public virtual IList<Group> Groups { get; set; }
}

public class Group
{
    public virtual Guid GroupId { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }

    public virtual IList<Role> Roles { get; set; }
    public virtual IList<Login> Logins { get; set; }
}

public class Role : ITerminable
{
    public virtual Guid RoleId { get; set; }
    public virtual string DisplayName { get; set; }
    public virtual string RoleName { get; set; }
    public virtual string Description { get; set; }
}

And an ERD that looks like this... Data Model ERD

This is my current query.

var login = loginRepository.Query().Where(x => x.Name == username).FetchMany(x=>x.Groups).ThenFetchMany(x=>x.Roles).SingleOrDefault();
return login.Groups.SelectMany(x => x.Roles).Distinct().ToList();

The problem is that while the first request to my site is always fine and goes through as a single query for the current user's Roles, subsequent ones result in NHibernate Profiler showing lots of cached queries (one for every role). I'm not entirely sure if this is a red flag or not (I'm using SysCache2, but it's not using Database Dependencies at the moment). But I would like to try and find a way to clear itup.

Is there a way to fix this so that I don't get a cache hit for every single role on every request when the first request was just one database hit? Or as an analogy, am I misinterpreting condensation on a pipe as a leak?

1

There are 1 answers

0
Diego Mijelshon On BEST ANSWER

Entity cache is separate from the query cache.

The query cache only stores the ids resulting from the query execution, so retrieving the entities back involves getting that list, and then getting all the values from the entity cache.