Skip to content

Latest commit

 

History

History
67 lines (58 loc) · 2.09 KB

README.md

File metadata and controls

67 lines (58 loc) · 2.09 KB

SqlBulkCopy wrapper with Dapper-like API

Build status NuGet

This library wraps SqlBulkCopy class with Dapper-like API. It provides extension methods for IDbConnection (just like Dapper do), but will only work for SqlConnection (for obvious reasons).

Usage Example

Table

CREATE TABLE [User] (
    Id int PRIMARY KEY IDENTITY,
    FirstName nvarchar(250),
    LastName nvarchar(250),
    Age int,
    Gender bit
)

POCO

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public bool Gender { get; set; }
}  

Code

IEnumerable<User> users = GetUsers();
connection.BulkInsert(users);

All properties will be automatically mapped to table columns as well as the type name will be mapped to table name.

Let's check:

// Using Dapper to Query users:
IEnumerable<User> inserted = connection.Query<User>("SELECT * FROM [User]");

// Assert
Assert.IsTrue(users.SequenceEqual(inserted, new UserComparer())); // true

Simple data to single column

List<byte[]> blobs = GetBinaryData();
connection.BulkInsert(blobs, tableName: "dbo.Data", columnName: "Blob");

Table and column names must be specified explicitly since they cannot be inferred from type/prop names.

Anonymous types

IEnumerable<DomainObject> domainObjects = GetData();
var dto = domainObjects
    .Select(obj => new
    {
        Foo = obj.Prop1,
        Bar = obj.Prop2.Normalize(),
        Baz = ConvertToBaz(obj.Prop3)
    });
    
connection.BulkInsert(dto, tableName: "FooBar");

Column names can be inferred from anonymous type props, but table name from type name cannot, so again it must be specified explicitly.