0

Well, i have a Model with a collection saving changes in a loop structure

foreach(Customer objCustomer in listCustomer)
{
    try
    {
        db.Customer.Add(objCustomer);
        db.SaveChanges();
    }
    catch(Exception ex)
    {
        db.Entry(objCustomer).State = EntityState.Detach;
    }
}

When it throws me any exception in a collection related to entity, the next ones keeps throwing exceptions.

I tried to detach the entire collection but it didn't work

foreach(Customer objCustomer in listCustomer)
{
    try
    {
        db.Customer.Add(objCustomer);
        db.SaveChanges();
    }
    catch(Exception ex)
    {
        for (int i = 0; i < objCustomer.Address; i++)
        {
            db.Entry(objCustomer.Address[i]).State = EntityState.Detach;
        }
        db.Entry(objCustomer).State = EntityState.Detach;
    }
}

Any suggestion?

Teta
  • 129
  • 9

3 Answers3

1

I don't know why but it works, i used like it refers in this post

EntityCollection Clear() and Remove() methods

objCustomer.Address.ToList().ForEach(x => db.Entry(x).State = EntityState.Detached);

It is almost as i did before using "for"

Thanks anyway everyone

Community
  • 1
  • 1
Teta
  • 129
  • 9
0

i thought that the exception of second code maybe has been never occurred?

In addition,your code has any transaction ?

0

Try this? Warning not tested!

using(var db = new Context())
{

    foreach(Customer objCustomer in listCustomer)
    {
         var exists = db.Customer.FirstOrDefault(x => x.CustomerID == objCustomer.CustomerID;

         if( exists = null)
         {
            db.Customer.Add(objCustomer);

         }
         else
         {
            db.Entry(objCustomer).State = EntityState.Modified;
         }
         db.SaveChanges();

    }

}
failedprogramming
  • 2,532
  • 18
  • 21
  • It did not work "The ObjectStateManager cannot track multiple objects with the same key" – Teta Mar 12 '14 at 15:19