我首先使用数据库,DbContext
并在DbContext
类中添加了一些与审计相关的代码,但是当我更新模型时,它删除了我在DbContext
类中编写的代码。请告诉我即使在模型更新后也如何保留此代码。
这是我的代码,并添加了注释,这些注释将在模型更新后删除:
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;
}
}
如果有人指导我会很棒
如果您查看该生成类的顶部,您将看到:
//------------------------------------------------------------------------------
// <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>
//------------------------------------------------------------------------------
这意味着该类将在每次更新时自动生成。
EF生成的类为partial
,您可以创建扩展/更改并将其添加到partial
该类的另一半(例如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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句