title: ASP.Net MVC Store User Entity In Session
body: <p>I am developing an ASP.Net MVC 3 Web application with Entity Framework 4. When a user logs into my application I would like to store their user entity (firstName, lastName etc) in a session which can then be access throughout the application. </p>
  
  <p>I understand that this may not be a good idea because when the ObjectContext closes/ disposes, then the User entity is detached and the user details could be lost.</p>
  
  <p>I thought another method could be, when the user logs in, assign the userID (Primary Key) to a session variable, ie:</p>
  
  <pre><code>HttpContext.Current.Session["currentUserID"] = user.userID;
  </code></pre>
  
  <p>Then create a class in the UserService class like so:</p>
  
  <pre><code>public static User CurrentUser
      {
  
          get
          {
              return Data.DBEntities.Users.Where(u =&gt; u.userID == HttpContext.Current.Session["currentUserID"]).FirstOrDefault();
          }
  
      }
  </code></pre>
  
  <p>Which should return a User Entity based on the currentUserID session variable. This isn't working for me however, I am getting a couple of errors</p>
  
  <pre><code>Cannot convert lambda expression to type 'string' because it is not a delegate type
  Delegate 'System.Func&lt;Asset.Model.User,int,bool&gt;' does not take 1 arguments
  </code></pre>
  
  <p>Is this approach I am taking correct, or is there a better way?</p>
  
  <p>Any feedback would be much appreciated.</p>