Search code examples
c#asp.net-mvcentity-frameworkef-database-first

How to prevent come code deletion in DbContext while updating model in database first Entity Framework


I have a database-first DbContext and I added some audit related code in the DbContext class, but when I update the model, it deleted my written code in DbContext class. Please tell me how to retain this code even after model update.

Here is my code and I added comments which code is deleting after model update:

public partial class MyDbContext : DbContext
{
    public MyDbContext()
        : base("name=ODbContext")
    {
    }

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

    public virtual DbSet<AspNotification> AspNotifications { get; set; }
    public virtual DbSet<ASPAudit> ASPAudit { get; set; }

    // this code is removed whenever I update model
    public override int SaveChanges()
    {
         var addedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added).ToList();
         
        int changes = base.SaveChanges();

        foreach (var entry in addedEntries)
        {
           ...some code
        }

        base.SaveChanges();

        return changes;
    }
}

It would be great if anyone guide me


Solution

  • If you look at top of that generated class, you'll see:

    //------------------------------------------------------------------------------
    // <auto-generated>
    //     This code was generated from a template.
    //
    //     Manual changes to this file may cause unexpected behavior in your application.
    //     Manual changes to this file will be overwritten if the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------
    

    That means this class will be auto-generated on every update.

    EF generated classes are partial, you can create and add your extensions/changes to other half of partial class (for example MyDbContextPartial.cs).

    // file MyDbContextPartial.cs
    public partial class MyDbContext
    {
        public override int SaveChanges()
        {
             var addedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added).ToList();
             
            int changes = base.SaveChanges();
            foreach (var entry in addedEntries)
            {
               ...some code
            }
    
            base.SaveChanges();
            return changes;
        }
    }