CSharp · Console
// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/bulk-insert
// @nuget: Z.EntityFramework.Extensions
// @nuget: EntityFramework
using System;
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
using Z.BulkOperations;
public class Program
{
public static void Main()
{
var customers = GenerateCustomers(5);
using (var context = new EntityContext())
{
var auditEntries = new List<AuditEntry>();
context.BulkInsert(customers, options => {
options.UseAudit = true;
options.AuditEntries = auditEntries;
});
SaveAuditChanges(auditEntries);
FiddleHelper.WriteTable("Saved Audit", context.AuditLogs);
}
}
public static void SaveAuditChanges(List<AuditEntry> auditEntries)
{
List<AuditLog> auditLogs = new List<AuditLog>();
foreach (var auditEntry in auditEntries)
{
AuditLog log = new AuditLog();
log.Action = auditEntry.Action.ToString();
log.TableName = auditEntry.TableName;
log.Values = string.Join("|", auditEntry.Values.Select(x => x.ColumnName + ";" + (x.OldValue ?? "") + ";" + (x.NewValue ?? "")));
log.Date = auditEntry.Date;
log.UserId = "my-user-id";
auditLogs.Add(log);
}
var context = new EntityContext();
// we turn off `AutoMapOutputDirection` as we don't need to return the identity values
context.BulkInsert(auditLogs, options => options.AutoMapOutputDirection = false);
}
public static List<Customer> GenerateCustomers(int count)
{
List<Customer> list = new List<Customer>();
for(int i = 0; i < count; i++)
{
list.Add(new Customer() { Name = "Customer_" + i});
}
return list;
}
public class EntityContext : DbContext
{
public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
{
}
public DbSet<Customer> Customers { get; set; }
public DbSet<AuditLog> AuditLogs { get; set; }
}
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
}
public class AuditLog
{
public int Id { get; set; }
public string Action { get; set; }
public string TableName { get; set; }
public string Values { get; set; }
public DateTime Date { get; set; }
public string UserId { get; set; }
}
}