CSharp · Console
// Dapper Plus
// Doc: https://dapper-plus.net/bulk-insert
// @nuget: Microsoft.Data.SqlClient
// @nuget: Z.Dapper.Plus
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.Data.SqlClient;
using Z.Dapper.Plus;
// Map your entity
DapperPlusManager.Entity<Post>()
.Table("Post")
.UseBulkOptions(x => {
x.InsertKeepIdentity = false;
x.AutoMapOutputDirection = true;
x.AutoMapOutputIdentity = true;
});
var posts = new List<Post>();
posts.Add(new Post() { Title = "Dapper Plus Options Beyond the Basics", URL = "https://codingsonata.com/dapper-plus-options-beyond-the-basics/" });
posts.Add(new Post() { Title = "Unleash the Power of Bulk Extensions with Dapper Plus", URL = "https://codingsonata.com/unleash-the-power-of-bulk-extensions-with-dapper-plus/" });
for (int i = 0; i < 10; i++)
{
posts.Add(new Post() { Title = i.ToString(), URL = "https://codingsonata.com/" });
}
var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer());
connection.CreateTable<Post>();
// Easy to use
//connection.UseBulkOptions(x =>
// x.InsertIfNotExists = true
//)
//.BulkInsert(posts);
connection.UseBulkOptions(x => {
//x.InsertKeepIdentity = true;
x.AllowDuplicateKeys = true;
}
)
.BulkInsert(posts);
//connection.UseBulkOptions(x =>
// x.AllowDuplicateKeys = true
//)
//.BulkInsert(posts);
//conection.UseBulkOptions(x =>
// x.BatchSize = 1000
//)
//.BulkInsert(posts);
foreach (var p in posts){
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(p));
}
[Table("Post")]
public class Post
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Title { get; set; }
public string URL { get; set; }
}