3
votes

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.

1

1 Answers

5
votes

Context.cs is not a class, it's a file, with one (or zero, or many) classes inside.

Just add a new cs File, for example CustomContext.cs,

and add

public partial class LocumEntities : DbContext {

    public override int SaveChanges()
    {
        //Audit Code Executes in Here
        return base.SaveChanges();
    }

    //other custom code (not generated by T4)
}

as it's partial, you can have part of LocumEntities class in many .cs files if you want, they will be considered as one class. Just be sure they're in the same namespace.

Never write your own code in a generated file...

Generated classes are generally partial just to enable that way to handle custom code.