A plugin for Microsoft.EntityFrameworkCore to support automatically recording data changes history.
AutoHistory
will recording all the data changing history in one Table
named AutoHistories
, this table will recording data
UPDATE
, DELETE
history.
- Install AutoHistory Package
Run the following command in the Package Manager Console
to install Microsoft.EntityFrameworkCore.AutoHistory
PM> Install-Package Microsoft.EntityFrameworkCore.AutoHistory
- Enable AutoHistory
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// enable auto history functionality.
modelBuilder.EnableAutoHistory();
}
}
- Ensure AutoHistory in DbContext
bloggingContext.EnsureAutoHistory()
You can use a custom auto history entity by extending the Microsoft.EntityFrameworkCore.AutoHistory class.
class CustomAutoHistory : AutoHistory
{
public String CustomField { get; set; }
}
Then register it in the db context like follows:
modelBuilder.EnableAutoHistory<CustomAutoHistory>(o => { });
Then provide a custom history entity creating factory when calling EnsureAutoHistory. The example shows using the
factory directly, but you should use a service here that fills out your history extended properties(The properties inherited from AutoHistory
will be set by the framework automatically).
db.EnsureAutoHistory(() => new CustomAutoHistory()
{
CustomField = "CustomValue"
});
Microsoft.EntityFrameworkCore.UnitOfWork had integrated this package.