title: MVC 5 global variable per user
body: <p>I've found that I have a lot of repeated code in all of my actions, and want to know the best way to avoid this. Say for example that each logged on user belongs to a school and I need to access this SchoolId in almost every action.</p>
  
  <p>They way I have it now almost every action will have a repeated database hit and need to reference my userService class...something like:</p>
  
  <pre><code>public ActionResult Index()
  {
  var schoolId = userService.GetSchoolId(User.Identity.GetUserId());
  var textBooksForSchool = textBookService.GetBooks(schoolId);
  ...
  }
  
  public ActionResult Delete()
  {
  var schoolId = userService.GetSchoolId(User.Identity.GetUserId());//all over the place
  var textBooksForSchool = textBookService.DeleteBooks(schoolId);
  ...
  }
  </code></pre>
  
  <p>I know that I can add the SchoolId to the claims but the syntax for returning it in every method is quite verbose (as far as I understand this avoids the db hit each time the claim is accessed?):</p>
  
  <p>In GenerateIdentityAsync:</p>
  
  <pre><code> var claims = new Collection&lt;Claim&gt;
          {           
          new Claim("SchoolId", User.SchoolId.ToString())
          };
  
          userIdentity.AddClaims(claims);        
  </code></pre>
  
  <p>In Action: </p>
  
  <pre><code>var SchoolId = Convert.ToInt32((User as ClaimsPrincipal).Claims.First(x =&gt; x.Type == "SchoolId").Value);   
  </code></pre>
  
  <p>Is there some kind of best practice here? Possibly storing the claim in a global variable on logon?</p>