批量插入:集合已修改;枚举操作可能无法执行

时间:2014-05-07 07:07:38

标签: c# ef-code-first bulkinsert

我正在使用此代码将数据保存到数据库中(我的数据来自一个文本文件,我使用Regex从该文件中提取字段):

var list = new List<IdiomExample>();
using (var db = new MyDbContext())
{
    foreach (Match match in r.Matches(input))
    {
        string val = match.Groups[1].Value;  // Idiom
        string val2 = match.Groups[2].Value; // Meaning
        string val3 = match.Groups[3].Value; // Desc
        foreach (Capture c in match.Groups["my"].Captures)
        {
            list.Add(new IdiomExample{Item = c.Value});
        }
        db.Idioms.Add(new Idiom
        {
            Verb = val,
            Meaning = val2,
            Description = val3,
            IdiomExamples = list
        });
        db.SaveChanges();
    }
}

但是当我运行我的代码时,我得到了这个例外:

Collection was modified; enumeration operation may not execute.

我的模特:

public class Idiom
{
    public Int32 Id { get; set; }
    public string Verb { get; set; }
    public string Meaning { get; set; }
    public string Description { get; set; }
    public IList<IdiomExample> IdiomExamples { get; set; }
}

public class IdiomExample
{
    public Int32 Id { get; set; }
    public string Item { get; set; }
}

当我检查我的表数据时,两个记录刚刚插入و,而它应该是Idioms表中的500条记录和IdiomExamples表中的大约1000条记录。我怎样才能解决我的问题呢? 提前致谢。

1 个答案:

答案 0 :(得分:1)

试一试:

using (var db = new MyDbContext())
{
    foreach (Match match in r.Matches(input))
    {
        var list = new List<IdiomExample>();

        string val = match.Groups[1].Value;  // Idiom
        string val2 = match.Groups[2].Value; // Meaning
        string val3 = match.Groups[3].Value; // Desc

        foreach (Capture c in match.Groups["my"].Captures)
        {
            list.Add(new IdiomExample{Item = c.Value});
        }

        db.Idioms.Add(new Idiom
        {
            Verb = val,
            Meaning = val2,
            Description = val3,
            IdiomExamples = list
        });
    }
    db.SaveChanges();
}