Update Multiple Table Rows in Service from a list viewmodel?

Viewed 79

I have a view model whose values ​​are sent as a list from the view for edit four input boxs ...

public class UpdatePollViewModel
{
    public List<string> Answer { get; set; }
}

In my service, I got the same values ​​from the database via Id:

public bool UpdatePoll(Guid id, UpdatePollViewModel viewModel)
{
    var polloption = _context.PollOptions.Where(p => p.PollId == Id).ToList();
}

I used this but it does not make sense because it repeats a lot!!!

 foreach (string item in viewModel.Answer)
 {
    foreach (var item2 in polloption)
    {
        item2.Answer = item;
        _context.SaveChanges();
    }
 }

What is the best way to handle this?

1 Answers

I'm going to assume that the magic number is 4.

There are 4 input boxes that are used to populate the view model list with 4 answers in the same order as the existing 4 answers that are retrieved from the database and you want to map the 4 inputs to the 4 records from the database.

var polloption = _context.PollOptions.Where(p => p.PollId == Id).ToList();

for (int i = 1; i <= 4; i++)
{
    polloption[i-1].Answer = viewModel.Answer[i-1];
}

_context.SaveChanges();
Related