EFCore.BulkExtensions icon indicating copy to clipboard operation
EFCore.BulkExtensions copied to clipboard

BulkInsert Ids Behaviour different than EF Core

Open stefanzilik-shell opened this issue 2 years ago • 1 comments

When inserting entities with EF Core, for auto-generated columns e.g. Identity, EF core is using value provided if the value is non-default (e.g. '2' instead of '0' for an int PK)

BulkInsert disregards the provided values and hence the insert behaves differently, and as a result referential integrity is broken

Is there any option to ask BulkInsert to behave the same as EF Core insert in regards to dealing with non-default auto generated values?

stefanzilik-shell avatar Dec 12 '23 14:12 stefanzilik-shell

How do you have configured identity, because regular EF insert (DB is empty prior to insert) when setting custom PK value throws:

SqlException: Cannot insert explicit value for identity column in table 'Item' when IDENTITY_INSERT is set to OFF.

Test:

[Fact]
public void RunInsertIdentity()
{
    ContextUtil.DatabaseType = SqlType.SqlServer;

    using var context = new TestContext(ContextUtil.GetOptions());
    var entities = new List<Item>();
    for (int i = 2; i < 10; i++)
    {
        var entity = new Item
        {
            ItemId = i, // 0 // when ItemId start from 2 throws exception
            Name = "name " + i,
            Description = string.Concat("info ", Guid.NewGuid().ToString().AsSpan(0, 3)),
            Quantity = i % 10,
            Price = i / (i % 5 + 1),
            TimeUpdated = DateTime.Now,
            ItemHistories = new List<ItemHistory>()
        };
        entities.Add(entity);
    }

    context.Items.AddRange(entities);
    context.SaveChanges();

    //context.BulkInsert(entities);
}

borisdj avatar Dec 28 '23 14:12 borisdj