CSharp · Console
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.SqlClient;
public class Program
{
public static void Main()
{
using (var context = new EntityContext())
{
context.Database.EnsureCreated();
}
using (var context = new EntityContext())
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer { Name = "ZZZ Projects", MaximumRequestPerDay = 100 });
customers.Add(new Customer { Name = "Jonathan Magnan" });
context.BulkInsert(customers, options => {
options.IncludeGraphBeta = true;
options.IncludeGraphOperationBuilder = builder =>
{
if(builder is Z.BulkOperations.BulkOperation<Customer> bulk)
{
// will use the value from the entities
bulk.ForceValueGeneratedStrategy = Z.EntityFramework.Extensions.ValueGeneratedStrategyType.OnAdd;
}
};
});
FiddleHelper.WriteTable("BulkInsert + ValueGeneratedStrategyType.Add will always insert entity values", context.Customers.AsNoTracking());
}
}
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(x => x.MaximumRequestPerDay).HasDefaultValueSql("50");
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public int MaximumRequestPerDay { get; set; }
}
}