EFE - Key - AllowDuplicateKeys

CSharp · Console

/Program.cs

// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/allow-duplicate-keys

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

using System;
using System.Linq;
using System.Data.Entity;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		GenerateData();
		
		var list = new List<Customer>() 
		{
			new Customer () { Name = "Customer_A", Description = "Description_updated_1" },
			new Customer () { Name = "Customer_A", Description = "Description_updated_2" },
			new Customer() { Name ="Customer_B", Description = "Description"}	
		};
	
		
		// AllowDuplicateKeys: Gets or sets if a duplicate key is possible in the source.
		using (var context = new EntityContext())
		{
			context.BulkMerge(list,options => 
			{
				options.ColumnPrimaryKeyExpression = customer => customer.Name;
				options.AllowDuplicateKeys = true;
			});

		
			FiddleHelper.WriteTable(context.Customers.ToList());
		}
	}
		 
	public static void GenerateData()
	{
		
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Name ="Customer_A", Description = "Description" });
			context.BulkSaveChanges();	
		}
		
		using (var context = new EntityContext())
		{
			FiddleHelper.WriteTable(context.Customers.ToList());	
		}
	}
	
	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; }
	}
}
;