EF Extensions - ForceValueGeneratedStrategy Option

CSharp · Console

/Program.cs

// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/forcevaluegeneratedstrategy-option

// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Extensions;

public class Program
{
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			context.Database.EnsureCreated();
		}
		
		using (var context = new EntityContext())
		{
			var customers = new List<Customer>();
			
			customers.Add(new Customer() { Name = "ZZZ Projects", TokenLimit = 200 });
			customers.Add(new Customer() { Name = "Jonathan Magnan"});

			context.BulkInsert(customers);

			FiddleHelper.WriteTable("1 - Without ValueGeneratedStrategyType", context.Customers.AsNoTracking().ToList());
		}	
		
		// CLEAR
		using (var context = new EntityContext())
		{
			context.Customers.DeleteFromQuery();
		}
		
		using (var context = new EntityContext())
		{
			var customers = new List<Customer>();
			
			customers.Add(new Customer() { Name = "ZZZ Projects", TokenLimit = 200 });
			customers.Add(new Customer() { Name = "Jonathan Magnan"});
			
			context.BulkInsert(customers, options => {
				options.ForceValueGeneratedStrategy = ValueGeneratedStrategyType.OnAddOrUpdate;
			});

			FiddleHelper.WriteTable("2 - With ValueGeneratedStrategyType", context.Customers.AsNoTracking().ToList());
		}
	}

	public class EntityContext : DbContext
	{
		public EntityContext() 
		{
		}

		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));

			base.OnConfiguring(optionsBuilder);
		}

		protected override void OnModelCreating(ModelBuilder modelBuilder)
		{
			modelBuilder.Entity<Customer>()
				.Property(c => c.TokenLimit)
				.HasDefaultValue(100);

			base.OnModelCreating(modelBuilder);
		}

		public DbSet<Customer> Customers { get; set; }
	}

	public class Customer
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
		public int TokenLimit { get; set; }
	}
}
;