0
foreach (var objUser in responseToken.SpecificUsers.SpecificUsers)
{
    flashObj.FlashSaleId = flashSalesObj.Id;
    flashObj.MappingId = Convert.ToInt32(objUser);
    flashObj.type = "Users";
    flashObj.CreatedOnUTC = DateTime.Now;

    _context.FlashSaleMapping.Add(flashObj);
    _context.SaveChanges();
}

I used this code first loop successfully saved when start; second time around, I get the error mentioned in the title.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
yashan
  • 1
  • 1
  • Your code is trying to save the same object over and over. Create *new* objects and *don't* call `SaveChanges` inside the loop. Use it only once, when you want to save *all* changes back to the database. That's how all ORMs work - changes are maintained locally and saved/committed in a single operation at the end. If you want to rollback changes, well,no changes have been made yet so you can just discard the context. You don't even need a transaction – Panagiotis Kanavos Nov 27 '19 at 14:07
  • Using EF propertly can result in orders of magnitude better performance - just 1 batched insert instead of 100 individual INSERTS and network roundtrips. No blocking due to long-lived transactions either – Panagiotis Kanavos Nov 27 '19 at 14:08

1 Answers1

0

You must create an new object in every loop

_context.SaveChanges(); generate an new id in the first loop but keep this id for all other loop. In addition to that this foreach loop add several time the same object.

foreach (var objUser in responseToken.SpecificUsers.SpecificUsers)
                    {
                        var newFlashSaleMapping = new FlashSaleMapping();
                        newFlashSaleMapping.FlashSaleId = flashSalesObj.Id;
                        newFlashSaleMapping.MappingId = Convert.ToInt32(objUser);
                        newFlashSaleMapping.type = "Users";
                        newFlashSaleMapping.CreatedOnUTC = DateTime.Now;
                        _context.FlashSaleMapping.Add(newFlashSaleMapping);

                    }
_context.SaveChanges(); //bulk sav
//LINQ version
var newFlashSaleMappings = responseToken.SpecificUsers.SpecificUsers.Select((flashSalesObj) = >
                    new FlashSaleMapping() {
                        FlashSaleId = flashSalesObj.Id,
                        MappingId = Convert.ToInt32(objUser),
                        type = "Users",
                        CreatedOnUTC = DateTime.Now                      
                    });
_context.FlashSaleMapping.AddRange(newFlashSaleMapping);
_context.FlashSaleMapping.SaveChanges();
Tohm
  • 305
  • 1
  • 5