简体   繁体   中英

ASP.NET Core SaveChangesAsync does not save everything

PROBLEM:

If I put SaveChangesAsync outside of the loop, it changes only the last data which was put with _context.Add(attdef);

Why is that so?

First I thought it's because I have autoIncrement, but when I disabled it, It still did not work.

Using SaveChanges instead of SaveChangesAsync does not fix problem aswell.

But updating data works well.

GameController.cs

for (int i = 0; i < editViewModel.TowerAttack.Count; i++) 
{
    tower = _context.Tower.First(m => m.TowerId == editViewModel.TowerId[i]);
    tower.Attack -= editViewModel.TowerAttack[i];
    _context.Update(tower);
    attdef.Id = 0; // AutoIncrement
    attdef.Amount = attackSum;
    _context.Add(attdef);
}

await _context.SaveChangesAsync(); 

Is attdef declared outside the loop? Are you just updating the same object with each loop? I would expect only the latest version of that object to be added if that's the case.

If you're trying to add several new objects, try declaring attdef within the loop so you're working with a new object each time.

I think you have declared attdef variable somewhere above and in the loop you're updating the same reference and adding it to the context. Due to this, you have single item adding in the context. The better way is to do it something like this

var attdefs = new List<Attdef>();
for (int i = 0; i < editViewModel.TowerAttack.Count; i++) 
            {
                tower = _context.Tower.First(m => m.TowerId == editViewModel.TowerId[i]);
                tower.Attack -= editViewModel.TowerAttack[i];
                _context.Update(tower);
                attdefs.Add(new AttacDef { id = 0, Amount = attackSum }) ;
            }
              _context.AddRange(attdefs); // don't remember exaxct syntaxt but this should be faster way
              await _context.SaveChangesAsync(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM