title: Saving and retrieving CreatedBy User information with EF7, MVC6, ASP.NET Identity
body: <p>I am using the latest MVC6 and Entity Framework 7, however I am sure many techniques used in MVC5 and Entity Framework 6 could help answer my question also.</p>
  
  <p>Almost all of the tables in my database have the following 4 fields for auditing:   CreatedDate, CreatedBy, ModifiedDate, ModifiedBy.</p>
  
  <p>I am trying to figure out which field from the built in IdentityUser (AspNetUsers table) I should be storing in the CreatedBy field when saving items to the database.</p>
  
  <p>I started by trying to use 'Username' since it is easily accessible by calling User.Identity.Name and passing it down to the repository when saving. Here is how I configured EF using Fluent API to help with retrieving the User who created an item along with all of their fields:</p>
  
  <pre><code>builder.Entity&lt;BlogPost&gt;()
      .Property(bp =&gt; bp.CreatedBy)
      .HasMaxLength(256);
  
  builder.Entity&lt;BlogPost&gt;()
      .HasOne(bp =&gt; bp.CreatedByUser)
      .WithMany()
      .HasForeignKey(bp =&gt; bp.CreatedBy)
      .HasPrincipalKey(u =&gt; u.UserName);
  </code></pre>
  
  <p>But then I noticed that Entity Framework yells when trying to add migrations and create the database because Username needs to be set as a primary key or it can't be used as a foreign key in another table.</p>
  
  <p>Then I got to the point where I figured I would just use the actual Id which is a GUID. The problem with this technique is that the Id of the current logged in user isn't easily available when trying to save: 'User.Identity.Name' is all that is there.</p>
  
  <p>Here are a couple of questions that I would like someone with EF and Auditing experience to try and answer for me:</p>
  
  <ol>
  <li><p>Do people even use Audit fields in all of their tables anymore? I don't see many others asking questions about this and Microsoft definitely doesn't make it easy to work with their new Identity system and custom audit fields.</p></li>
  <li><p>Should I be storing Username or Id in my CreatedBy field. Some say this might be preference but I really want to know what direction Microsoft might be pushing with the new Identity. The problem with storing Id is that it is hard to get it when saving and the problem with storing Username is that it isn't a primary key in AspNetUsers table.</p></li>
  <li><p>I really would just like to know of a good pattern in general when using EF that handles auditing when saving, and retrieving the User and setting it as a Navigation property on my entities that need it when pulling records from the database.</p></li>
  </ol>