How can I insert multiple lines into a foreach command using LINQ?

I wrote these lines:

foreach (var catId in CatIds)
{
    AdCategory.AdId = LastAd.AdID;
    AdCategory.CategoryId = catId;
    EngineDB.Ad_Categories.InsertOnSubmit(AdCategory);
    EngineDB.SubmitChanges();
}

      


and CatIds is an array of integers.
this command correctly inserts the first element, but the next loop throws this exception:
"Unable to add entity that already exists.
How can I fix this.
Please help me as soon as possible!"

0


a source to share


2 answers


You need to create a new AdCategory in a loop. Otherwise, as the error states, you will be inserting the same object over and over.

You must also move



EngineDB.SubmitChanges();

      

outside of the loop, so you only make one call to the database.

+1


a source


as Jimmy said you need to create a new AdCategory in a loop. You also probably don't want to call the SubmitChanges method every time, this call uses a transaction to make sure all items are added at once or not at all.

Try something like:



foreach (var catId in CatIds)
{
    var AdCategory = new AdCategory()
    {
        AdId = LastAd.AdID,
        CategoryId = catId
    }
    EngineDB.Ad_Categories.InsertOnSubmit(AdCategory);
}

EngineDB.SubmitChanges();

      

+6


a source







All Articles