I am building an ASP.Net MVC 3 Web application with Entity Framework 4.1. I am using the Database First approach.
I have also used the ADO.NET DbContext Generator in order to create POCO classes as opposed to using the auto generated Entity Objects. When you use the ADO.NET DbContext Generator it will create two new items, a .tt file which generates the POCO classes for each Entity, and also a .Context.tt file which generates a derived DbContext class (used for querying and persisting data).
In my application I have written code to perform Auditing for particular Entities, this code executes inside the override SaveChanges() method I have created. I have placed this override SaveChanges() method inside the Context.cs class as follows and it works nicely
public partial class LocumEntities : DbContext
{
public LocumEntities()
: base("name=LocumEntities")
{
}
public override int SaveChanges()
{
//Audit Code Executes in Here
return base.SaveChanges();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Audit> Audits { get; set; }
public DbSet<Form> Forms { get; set; }
//Other DbSets
}
However, anytime I even move or update an Entity in my EDMX Diagram, and then save, my custom SaveChanges() method inside the Context.cs class is deleted. Is there any way I can stop this from happening, or maybe I should be putting my SaveChanges() method elsewhere?
Can someone please advise?
Thanks.