title: Attaching user to entities in MVC application with .NET Membership
body: <p>In my Entity Framework, MVC application I am using .Net Membership (I wrote a custom provider). My questions are:</p>
  
  <ol>
  <li>How do I best handle attaching the user to entities I create?</li>
  <li>Is it acceptable to attach navigation properties to my User Entity that extends IPrincipal or should I be keeping it "clean"?</li>
  </ol>
  
  <p>Currently in every action in which I attach a new entity to a user, I first have to look-up the user. Then frequently, because I do not have navigation properties on my User, I need to do a second query to get results from a different DbSet?</p>
  
  <p>So simplifying, a controller could look like:</p>
  
  <pre><code>public ActionResult Index() {
          User u = UserRepository.FindById((int)Membership.getUser().ProviderUserKey);
          List&lt;OtherObject&gt; oList = OtherRepository.FindByUser(u);
  }
  </code></pre>
  
  <p>What I would like to do is something like:</p>
  
  <pre><code>public ActionResult Index() {
          List&lt;OtherObject&gt; oList = provider.User.OtherObjectList;
          // or
          List&lt;OtherObject&gt; oList = Membership.GetUser().OtherObjectList;
  }
  </code></pre>
  
  <p>But I am not sure this would be correct with respect to how I should use membership (with the user only holding login/account required information.</p>
  
  <p>And a final question on this, this is how my membership user is currently being returned:</p>
  
  <pre><code>public override MembershipUser GetUser(string username, bool userIsOnline) {
          User u = UserRepository.FindByUsername(username);
          MembershipUser memU = null;
          if (u != null) {
              // 
              memU = new MembershipUser("MyMembershipProvider",
                          username, u.UserID, u.Email, string.Empty,
                          u.Comment, u.IsApproved, u.IsLockedOut, u.CreationDate,
                          u.LastLoginDate, u.LastActivityDate, u.LastPasswordChangeDate,
                          u.LastLockedOutDate);
          }
          return memU;
      }
  </code></pre>
  
  <p>So I look up the user and create a new <code>MembershipUser</code>, which I then use to immediately look up the user again in the controller - seems a bit redundant, but is this just what I should do?</p>