using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using Z.EntityFramework.Plus;
using System.Threading.Tasks;
public static void Main()
using (var context = new EntityContext())
context.Database.EnsureCreated();
AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
(context as EntityContext).AuditEntries.AddRange(audit.Entries);
using (var context = new EntityContext())
var listToRemove = context.Customers.Where(x => x.IsActive == false ).ToList();
var listToModify = context.Customers.Where(x => x.IsActive == true ).ToList();
var listToAdd = new List<Customer>() { new Customer() { Name = "Customer_C", Description = "Description", IsActive = false}};
context.Customers.AddRange(listToAdd);
context.Customers.RemoveRange(listToRemove);
listToModify.First().Description = "Updated_A";
using (var context = new EntityContext())
FiddleHelper.WriteTable("All Entry",context.AuditEntries.ToList());
foreach(var entry in context.AuditEntries.ToList())
FiddleHelper.WriteTable("Properties for Entry ID: " + entry.AuditEntryID,context.AuditEntryProperties.Where(x => x.AuditEntryID == entry.AuditEntryID).ToList());
public static void GenerateData()
using (var context = new EntityContext())
context.Customers.Add(new Customer() { Name ="Customer_A", Description = "Description", IsActive = true });
context.Customers.Add(new Customer() { Name ="Customer_B", Description = "Description", IsActive = false });
public class EntityContext : DbContext
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
base.OnConfiguring(optionsBuilder);
public DbSet<AuditEntry> AuditEntries { get; set; }
public DbSet<AuditEntryProperty> AuditEntryProperties { get; set; }
public DbSet<Customer> Customers { get; set; }
public override int SaveChanges()
audit.PreSaveChanges(this);
var rowAffecteds = base.SaveChanges();
if (audit.Configuration.AutoSavePreAction != null)
audit.Configuration.AutoSavePreAction(this, audit);
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken)
audit.PreSaveChanges(this);
var rowAffecteds = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (audit.Configuration.AutoSavePreAction != null)
audit.Configuration.AutoSavePreAction(this, audit);
await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
public int CustomerID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Boolean IsActive { get; set; }