EFE - Request - PreBulkSynchronize

CSharp · Console

/Program.cs

// @nuget: EntityFramework
// @nuget: Z.EntityFramework.Extensions

using System;
using System.Linq;
using System.Data.Entity;
using System.Collections.Generic;
using Z.EntityFramework.Extensions;

public class Program
{
	public static void Main()
	{
		GenerateData();
		EntityFrameworkManager.PreBulkSynchronize = (ctx, obj) => 
		{
			if(obj is IEnumerable<Customer>) 
			{
				foreach(var customer in (IEnumerable<Customer>)obj)
				{
					if (customer.CustomerID == 0)
            		{
                		customer.CreatedDate = DateTime.Now;
            		}
            		else
            		{
                		customer.ModifiedDate = DateTime.Now;
            		}
				}
			}
		};
		
		using (var context = new EntityContext())
		{
			FiddleHelper.WriteTable("Before_BulkSynchronize", context.Customers.ToList());
			
			var list = context.Customers.Take(2).ToList();
			
			list.ForEach(x => { x.Name += "_Updated"; x.IsActive = false; });
			
			list.Add(new Customer()	{ Name ="Customer_E", IsActive = true});
			list.Add(new Customer()	{ Name ="Customer_F", IsActive = true});
			
			context.BulkSynchronize(list);
		}
		
		using (var context = new EntityContext())
		{
			FiddleHelper.WriteTable("After_BulkSynchronize", context.Customers.ToList());
		}
	}
	
	public static void GenerateData()
	{	
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Name ="Customer_A", IsActive = true });
			context.Customers.Add(new Customer() { Name ="Customer_B", IsActive = true });
			context.Customers.Add(new Customer() { Name ="Customer_C", IsActive = true });
			context.Customers.Add(new Customer() { Name ="Customer_D", IsActive = true });

			context.BulkSaveChanges();	
		}
	}

	public class EntityContext : DbContext
	{
		public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
		{

		}
		
		public DbSet<Customer> Customers { get; set; }
	}
	
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
		public Boolean IsActive { get; set; }
		public DateTime? CreatedDate { get; set; }
		public DateTime? ModifiedDate { get; set; }
	}
}
;