批量插入数据entity framework 7

Bulk insert data entity framework 7

通常在我以前的项目中,我可以通过将对象列表作为下面的代码传递来进行批量插入

public void Create(List<ApplicationUserRole> item)
{           
        foreach (var data in item)
        {
            _dbContext.ApplicationUserRole.Add(data);
        }
        _dbContext.SaveChanges();           
}

但现在我一直报错

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.

我需要更改下面的代码才能工作

    foreach (var data in item)
    {
        _dbContext.ApplicationUserRole.Add(data);
        _dbContext.SaveChanges();
    }

我知道这是非常糟糕的做法。插入大量数据性能会很慢

这个问题有什么解决办法吗?

您看到的异常消息可能无法通过在每次添加后调用 "SaveChanges" 来修复。问题的根本原因是您的 DbContext 实例已经有一个具有相同键的 ApplicationUserRole 实体(猜测它是 ApplicationUserRole.Id 或其他)。 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 例如。)

如果错误不是是由不正确设置临时键值引起的,那么还要确保您的 DbContext 实例是短暂的并且只在一个线程中使用。换句话说,只对一个操作使用 DbContext。

public void Create(List<ApplicationUserRole> item)
{         
    using (var context = new MyContext())
    {  
        context.ApplicationUserRole.AddRange(data);
        context.SaveChanges();  
    }         
}