title: Assigning [Key] attribute to Entity Framework generated class - MVC4 C#
body: <p>I am working on an MVC 4 (C#) project in Visual Studio 2012.  I am using the Entity Framework which utilizes an *.edmx file to model an existing database.  My goal is to implement database auditing to track any changes being made to the database.  Classes are generated automatically with the fields from the database tables - pretty standard stuff, I believe.</p>
  
  <p>I am running into a problem when attempting to retrieve the primary key of these generated classes.  The Entity Framework does not assign the [Key] attribute to the class properties.  I attempted to solve this by extending the partial classes that were created and assigning this attribute myself. Adding it directly to the generated class works fine.  If I try the "buddy class" method, I get the following error later on in my code execution: "Entity {Class Name} has no [Key] attribute."</p>
  
  <p>Auto-Generated class:</p>
  
  <pre><code>public partial class List
  {
     public List()
     {
         this.Tasks = new HashSet&lt;Task&gt;();
     }
  
     public int Id { get; set; }
     public string ListName { get; set; }
  }
  </code></pre>
  
  <p>Extension (buddy) class:</p>
  
  <pre><code>[MetadataType(typeof(ListMetaData))]
  public partial class List
  {
  
      private class ListMetaData 
      {
          [Key]
          public int Id { get; set; }
  
      }
  
  }
  </code></pre>
  
  <p>Code snippet:</p>
  
  <pre><code>var property = dbEntry.Entity.GetType().GetProperties().FirstOrDefault(
     p =&gt; p.GetCustomAttributes(typeof(KeyAttribute), true).Any());
  
  if (property == null)
      throw new InvalidOperationException(string.Format(
      "Entity {0} has no [Key] attribute.", dbEntry.Entity.GetType().Name));
  
  string keyName = property.Name; 
  </code></pre>
  
  <p>I am overriding the SaveChanges() method in DbContext to track the changes being made. The snippet above shows a portion of code from a function that examines a DbEntityEntry object (dbEntry) to get the primary key.</p>