Normally In my previous project, I can do bulk insert by passing a list of object as code below
public void Create(List<ApplicationUserRole> item)
{
foreach (var data in item)
{
_dbContext.ApplicationUserRole.Add(data);
}
_dbContext.SaveChanges();
}
But for now i keep hitting error
InvalidOperationException: The instance of entity type 'Docdoc.Models.ApplicationUserRole' cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.
I need change my code at below to work
foreach (var data in item)
{
_dbContext.ApplicationUserRole.Add(data);
_dbContext.SaveChanges();
}
I know It is very bad practice. The performance will be very slow by insert large amount of data
Any solution for this problem?
The exception message you saw may not be fixed by calling "SaveChanges" after each Add. The root cause of your problem is that your instance of DbContext already has a ApplicationUserRole entity with the same key (guessing it is ApplicationUserRole.Id or something). This error is common and is often caused by manually setting temporary key values, e.g. setting ApplicationUserRole.Id to -1. (See https://github.com/aspnet/EntityFramework/issues/4488 for example.)
If the error is not being caused by incorrectly setting temp key values, then also make sure your instance of DbContext is short-lived and only used in one thread. In other words, use DbContext for one operation only.
public void Create(List<ApplicationUserRole> item)
{
using (var context = new MyContext())
{
context.ApplicationUserRole.AddRange(data);
context.SaveChanges();
}
}