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

BulkSaveChanges throws "is already being tracked" exception #1628

Open
Ben555555 opened this issue Dec 5, 2024 · 2 comments
Open

BulkSaveChanges throws "is already being tracked" exception #1628

Ben555555 opened this issue Dec 5, 2024 · 2 comments
Labels

Comments

@Ben555555
Copy link

Ben555555 commented Dec 5, 2024

I'm using the following code:

dbContext.Translations.Add(new TranslationEntity());

dbContext.BulkSaveChanges();

dbContext.Users.Add(newUserEntity());

dbContext.SaveChanges();

On the normal SaveChanges (The second one) call I get the following exception:

System.InvalidOperationException: The instance of entity type 'TranslationEntity' cannot be tracked because another instance with the key value '{Id: 5652fb85-6fbc-40fd-4914-08dd152b7ad7}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

This probably means that it tries to track this entity again somehow. Is it possible to combine both methods in sequence?

@Gilbert1391
Copy link

I ran into this and spent so much time looking for a solution. The only solution I found for this problem is to attach the entitie after calling BulkSaveChanges() to let EF know the entity already exist in the database, like so:

var translation = new TranslationEntity();
dbContext.Translations.Add(translation);
dbContext.BulkSaveChanges();
dbContext.Translations.Attach(translation)
dbContext.SaveChanges();

This method is buggy.

@borisdj
Copy link
Owner

borisdj commented Dec 5, 2024

What version of lib are you using, and it this for SqlServer?
Can you make a test to reproduce the issue.
I have added the following one and it passed:

[Theory]
[InlineData(SqlType.SqlServer)]
public void SaveChanges2TimesTest(SqlType dbServer)
{
   ContextUtil.DatabaseType = sqlType;
    using var context = new TestContext(ContextUtil.GetOptions());

    context.Departments.Add(new Department { Id = Guid.NewGuid(), Name = "D1" });
    context.BulkSaveChanges();

    context.Customers.Add(new Customer { Name = "Ca" });
    context.SaveChanges();
}

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

3 participants