0

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(); 

2 Answers 2

1

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(); 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.