Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BulkInsert Ids Behaviour different than EF Core #1353

Open
stefanzilik-shell opened this issue Dec 12, 2023 · 1 comment
Open

BulkInsert Ids Behaviour different than EF Core #1353

stefanzilik-shell opened this issue Dec 12, 2023 · 1 comment
Labels

Comments

@stefanzilik-shell
Copy link

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?

@borisdj
Copy link
Owner

borisdj commented Dec 28, 2023

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);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants