简体   繁体   English

批量插入数据实体框架7

[英]Bulk insert data entity framework 7

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. InvalidOperationException:无法跟踪实体类型'Docdoc.Models.ApplicationUserRole'的实例,因为已经跟踪了具有相同键的该类型的另一个实例。 For new entities consider using an IIdentityGenerator to generate unique key values. 对于新实体,请考虑使用IIdentityGenerator生成唯一的键值。

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. 您看到的异常消息可能无法通过在每次添加后调用“ SaveChanges”来解决。 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). 问题的根本原因是,您的DbContext实例已经具有带有相同密钥的ApplicationUserRole实体(猜测为ApplicationUserRole.Id或其他名称)。 This error is common and is often caused by manually setting temporary key values, eg setting ApplicationUserRole.Id to -1. 此错误很常见 ,通常是由手动设置临时键值引起的,例如,将ApplicationUserRole.Id设置为-1。 (See https://github.com/aspnet/EntityFramework/issues/4488 for example.) (例如,请参见https://github.com/aspnet/EntityFramework/issues/4488 。)

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. 如果该错误不是由于错误地设置了临时键值引起的,则还应确保DbContext实例是短暂的并且仅在一个线程中使用。 In other words, use DbContext for one operation only. 换句话说,仅对一个操作使用DbContext。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM