Effectively cache identity related objects

I am using asp.net MVC5 and asp.net Identity v2 (from nightly releases), but I think this question still applies to Identity V1.

I have a membership system, and I associate an object AspNetUserwith my object membershipuserthrough a field AspUserIdin a table membershipuser.

public partial class membershipuser
{
    public int id { get; set; }
    public string full_name { get; set; }
    public string address { get; set; }
    public string AspNetUserId { get; set; }
    .....
}

I was wondering what is the best way to cache memberuser entries for the life of the request. In this way:

public static class extensions
    {
        public static membershipuser GetMember(this System.Security.Principal.IPrincipal User)
        {
            string currentUserId = User.Identity.GetUserId();
            return new MemberEntities().membershipusers.FirstOrDefault(m => m.AspNetUserId == currentUserId );
        }
    }

Or so:

 public abstract partial class BaseController : Controller
{
    private membershipuser _Member;

    public membershipuser Member
    {
        get { 
            if(_BASRaTMember == null)
            {
               string currentUserId = User.Identity.GetUserId(); 
                BASRaTMember = new BasratEntities().tbl_basrat_members.FirstOrDefault(m => m.AspNetUserId == currentUserId );
            }
            return _BASRaTMember; 
        }
        private set { _BASRaTMember = value; }
    }

}

I think the Basecontroller method is the best, since I assume that if I call the extension method 5 times to check the properties of the element, it will query the database for the user 5 times. Or would it be better to somehow save him against the request? My only goal is to reduce the database search for queries after user authentication.

+4
1

, 2.0, samples, DbContext (OwinContext), DbContext . UserId, , - . , .. -

public async Task<TUser> GetUser(this IOwinContext context, TKey userId, UserManager<TUser, TKey> manager) {
      var contextKey = "computeYourCacheKey"+userId;
      var user = context.Get<TUser>(contextKey);
      if (user == null) {
          user = await manager.FindByIdAsync(userId);
          context.Set<TUser>(userId, user);
      }
      return user;
}
0

Source: https://habr.com/ru/post/1529950/


All Articles