I have two tables - QuestionOptions and Answers. There's a many to many relationship between the two. I'm trying to remove QuestionOptions pertaining to a specific Question, and need to remove the answers first. Here's my code:
using (Survey_Context _context = new Survey_Context())
{
IQueryable<QuestionOption> questionOptions = _context.QuestionOptions.Where(qo => qo.QuestionID == questionID);
foreach (QuestionOption questionOption in questionOptions.ToList())
{
foreach (Answer answer in questionOption.Answers)
questionOption.Answers.Remove(answer);
_context.SaveChanges();
}
_context.QuestionOptions.RemoveRange(questionOptions.ToList());
_context.SaveChanges();
}
This causes the following:
Error - System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
What am I missing here?
There are two main problems in your code.
First, the error that is causing the Invalid Operation Exception you are seeing :
You are trying to remove element of a list that you are iterating on !
You should not modify a list (I mean : add or delete elements) that you are enumerating (with a foreach, like in your code) .
That is simply not valid this way.
Second, there is an error of logic :
If you want to delete elements, then you want to delete this objects from the database context , not remove them from some list that you just created.
As suggested in comments, you can correct both of these errors in one go by replacing :
foreach (Answer answer in questionOption.Answers)
questionOption.Answers.Remove(answer);
by
_context.Answers.RemoveRange(questionOption.Answers);
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.