如何在首先更新数据库中的模型时防止 DbContext 中的代码删除 Entity Framework

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

我有一个数据库优先 DbContext 并且我在 DbContext class 中添加了一些与审计相关的代码,但是当我更新模型时,它删除了我在 [= =12=] class。请告诉我如何在模型更新后保留此代码。

这是我的代码,我添加了模型更新后删除代码的注释:

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;
    }
}

如果有人指导我就太好了

如果您查看生成的 class 顶部,您会看到:

//------------------------------------------------------------------------------
// <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>
//------------------------------------------------------------------------------

这意味着这个 class 将在每次更新时自动生成。

EF 生成的 classes 是 partial, you can create and add your extensions/changes to other half of partial class(例如 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;
    }
}