zzzprojects / Bulk-Operations

C# SQL Bulk Operations | High-performance C# bulk insert, update, delete and merge for SQL Server, SQL Azure, SQL Compact, MySQL, and SQLite.
https://bulk-operations.net
142 stars 36 forks source link

BulkInsert errors when using InsertIfNotExists and ColumnMappings. #49

Closed codyspeck closed 5 years ago

codyspeck commented 5 years ago

Given the following table in SQL Server:

CREATE TABLE Product (
    Name nvarchar(50) null
);

The following code throws an error:

class Product
{
    public string Name { get; set; }
}

static void InsertBroken()
{
    using (var connection = new SqlConnection(ConnectionString))
    using (var bulk = new BulkOperation(connection))
    {
        connection.Open();

        var products = new List<Product>
        {
            new Product { Name = "Name" }
        };

        bulk.ColumnMappings = new List<ColumnMapping>
        {
            new ColumnMapping("Name", "Name")
        };
        bulk.DestinationTableName = "Product";
        bulk.AutoMapKeyName = "Name";
        bulk.InsertIfNotExists = true;

        bulk.BulkInsert(products);
    }
}

"System.Exception: 'An error occured, no primary key could be found or resolved.'"

If the ColumnMappings aren't set, then this code works fine. The ColumnMapping is not needed for this example, but they are for my actual use case.

Is there anything I can do to get around this or is this a bug?

JonathanMagnan commented 5 years ago

Hello @codyspeck ,

It works as expected.

Anything with the prefix AutoMap only are taken if there is no mapping. In other words, the auto mapping only happens if there is no mapping.

If you specify the mapping, you should be able to specify that the column is also a key

bulk.ColumnMappings = new List<ColumnMapping>
        {
            new ColumnMapping("Name", "Name", true)
        };

Let me know if that explains correctly why this behavior is not a bug but something working as intended.

Best Regards,

Jonathan

codyspeck commented 5 years ago

Ah, that works perfectly. Thank you for clearing that up for me!