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.
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."
Auto-Generated class:
public partial class List
{
public List()
{
this.Tasks = new HashSet<Task>();
}
public int Id { get; set; }
public string ListName { get; set; }
}
Extension (buddy) class:
[MetadataType(typeof(ListMetaData))]
public partial class List
{
private class ListMetaData
{
[Key]
public int Id { get; set; }
}
}
Code snippet:
var property = dbEntry.Entity.GetType().GetProperties().FirstOrDefault(
p => 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;
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.
Thanks for the suggestions everyone. What I ended up doing is modifying the *.tt template to automatically add the [Key] Attribute and the System.ComponentModel.DataAnnotations Directive to dynamically generated class files.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments