How to preserve the Model.Context.cs file header content after updating model from db with Entity Framework?

StackOverflow https://stackoverflow.com/questions/17749788

Question

The Model.Context.cs file is automatically generated when using Entity Framework Database First.

I have modified the header part of the class to be compatible with a Unit of Work and Repository pattern:

public partial class MyDatabaseContext : DbContext, IDbContext
{
    public MyDatabaseContext()
        : base("name=MyDatabaseContextEntities")
    {
        // disable lazy loading for best practices - keeps from accidentaly loading large entity graphs
        Configuration.LazyLoadingEnabled = false;
    }

    // refactored
    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }

    public override int SaveChanges()
    {
        // this.ApplyStateChanges();
        return base.SaveChanges();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }
    .
    .
    .

The issue is that whenever I update the model from the db, obviously, this file gets overwritten.

I've saved the relevant code in a commented out portion of the *.config, and simply copy/paste it back in place whenever the model is updated.

Even though the model is not updated that frequently, I'd like to know if there is a way of preserving this content so I don't have to go through the extra step of copy/pasting.

Was it helpful?

Solution

For the added members, you can create another file that contains another partial of the class. This new file won't be overwritten so anything you've added there should persist between updates.

For the changes that aren't new members (like the added line in the constructor), you can edit the Model.Context.tt file directly. This is a simple T4 Text Template used to re-generate the code when the model is updated. It is similar to an ASP.NET page; however, instead of using C# to generate HTML, it uses C# to generate more C#.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top