EF批量插入会创建重复项

时间:2017-01-27 18:20:49

标签: c# entity-framework entity-framework-6

我正在尝试构建一个可以填充我的测试数据库的工具。从本质上讲,它是一个批量插入分成20个批次(现在),因为随着它的增长,上下文似乎变得越来越慢。

int records = 43;
int disposeAfter = 20;
var _localContext = new DB(false);
_localContext.Configuration.AutoDetectChangesEnabled = false;

for (int i = 1; i <= records; i++)
 {    
     Communication item = new Communication();
     ....set all the item properties, etc..

    _localContext.Communications.Add(item);
    if (i % disposeAfter == 0)
       {
           _localContext.SaveChanges();
           _localContext.Dispose();               
           _localContext = new DB(false);
           _localContext.Configuration.AutoDetectChangesEnabled = false;
        } 
} 
_localContext.SaveChanges();

问题是在此之后。我在数据库中有超过43条记录。我逐步完成循环,似乎在第一个saveChanges()调用之后,_localContext.Communications.Add(item);调用有可能将已经插入的一些记录与第一个saveChanges()调用一起拉入上下文。然后,当其他saveChanges()来电时,再次保存。

我很茫然...... 以下是我的DB课程。

public class DB : DbContext
{
    public DbSet<EF.Communication.Communication> Communications { get; set; }

    public DB()
    {
        this.Database.Log = s => Debug.WriteLine(s);
    }

    public DB(bool verbose)
    {
        if (verbose)
            this.Database.Log = s => Debug.WriteLine(s);
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
        modelBuilder.Configurations.Add(new CommunicationConfig());

        base.OnModelCreating(modelBuilder);
    }
}

0 个答案:

没有答案