Skip to content

Instantly share code, notes, and snippets.

internal const string InsertStagingTable = @"MERGE INTO EntitySimples AS DestinationTable
USING
(
{StagingTable}
) AS StagingTable
ON 1 = 2
WHEN NOT MATCHED THEN
INSERT ( ColumnInt )
VALUES ( ColumnInt )
;";
private static void BulkInsertBulkCopy(List<EntitySimple> list)
{
var dt = ToDataTable(list);
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.FireTriggers, null))
{
internal const string InsertStagingTableWithOutput = @"MERGE INTO EntitySimples AS DestinationTable
USING
(
SELECT ZZZ_Index, ColumnInt FROM {TemporaryTable} WHERE ZZZ_Index >= @IndexStart AND ZZZ_Index < @IndexEnd
) AS StagingTable
ON 1 = 2
WHEN NOT MATCHED THEN
INSERT ( ColumnInt )
VALUES ( ColumnInt )
OUTPUT
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace Z.EntityFramework.Extensions
{
public class HowTo_BulkInsert_InSqlServer
{
// Entity Framework Extensions Library
// BulkInsert extension methods is added automatically
using (var ctx = new EntitiesContext())
{
ctx.BulkInsert(list);
}
var customer = new Association_OneToMany_Left();
var order = new Association_OneToMany_Right();
order.Left = customer;
using (var ctx = new TestContext())
{
ctx.Association_OneToMany_Rights.Add(order);
// DO NOT save in the database.
var customer = new Association_OneToMany_Left();
var order1 = new Association_OneToMany_Right();
var order2 = new Association_OneToMany_Right();
order1.Left = customer;
order2.Left = customer;
using (var ctx = new TestContext())
{
// Adding the first order create a new order list in the customer entity
db.Customers
.Where(x => "x.City == city && x.Orders.Count >= count",
new { city = "London", count = 10 })
.OrderBy(x => "x.CompanyName")
.Select(x => "new { Name = x.CompanyName, x.Phone }");
db.Customers
.Execute(@"Where(x => x.City == city && x.Orders.Count >= count)
.OrderBy(x => x.CompanyName)
.Select(x => new { Name = x.CompanyName, x.Phone })",
db.Customers
.Where("City == @0 and Orders.Count >= @1", "London", 10)
.OrderBy("CompanyName")
.Select("New(CompanyName as Name, Phone)");
-- CREATE test table
DECLARE @SourceTable TABLE
(
RowID INT ,
DelimitedString VARCHAR(8000)
)
INSERT INTO @SourceTable
VALUES ( 1, 'a ; b' ),
( 2, 'a; b ; c' )