Dapper Plus - Bulk Insert

    Example - Insert Single

    INSERT a single entity with Bulk Operation.

    Try it: .NET Core |

    INSERT many entities with Bulk Operation.

    1. using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
    2. {
    3. connection.BulkInsert(customers);
    4. }

    Try it: .NET Core |

    Example - Insert with relation (One to One)

    Try it: | .NET Framework

    INSERT entities with a one to many relations with Bulk Operation.

    1. DapperPlusManager.Entity<Supplier>().Table("Suppliers").Identity(x => x.SupplierID);
    2. DapperPlusManager.Entity<Product>().Table("Products").Identity(x => x.ProductID);
    3. {
    4. connection.BulkInsert(suppliers).ThenForEach(x => x.Products.ForEach(y => y.SupplierID = x.SupplierID)).ThenBulkInsert(x => x.Products);
    5. }

    Try it: | .NET Framework

    Real-Life Scenarios

    Your entity has an identity property, but you want to force it to insert a specific value instead. The InsertKeepIdentity option allows you to keep the identity value of your entity.

    Insert without returning the identity value

    By default, the BulkInsert method already returns the identity when inserting.

    However, such behavior impacts performance. For example, when the identity must be returned, a temporary table is created in SQL Server instead of directly using SqlBulkCopy into the destination table.

    You can improve your performance by turning off the AutoMapOutput option.

    1. using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
    2. {
    3. connection.UseBulkOptions(options => options.AutoMapOutputDirection = false).BulkInsert(customers);
    4. FiddleHelper.WriteTable("1 - Customers (from list)", customers);

    Try it: | .NET Framework