Question

I'm using this code for saving data into database (my data comes from a text file that I extract fields in that file using 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();
    }
}

but when I run my code I get this exception :

Collection was modified; enumeration operation may not execute.

My models :

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; }
}

when I check my table's data two records just insertedو Whereas it should be 500 records in Idioms's Table and about 1000 records in IdiomExamples's Table. How can I solve my problem?
Thanks in advance.

Was it helpful?

Solution

give it a shot:

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top