In the following code, I receive an error in _context.SaveChanges(); when adding a new record to FeedbackComments inside the first foreach loop. The error is New transaction is not allowed because there are other threads running in the session.. Any ideas why this is happening?
BTW, I keep receiving the same error when SaveChanges is called only once after the outer loop.
List<FeedbackComment> feedbackComments = comments.Select(c => new FeedbackComment
{
Id = c.Id,
CommentText = c.Content,
SubmissionId = submissionId,
UserDisplayName = c.Author.DisplayName,
DateCreated = c.CreatedTime.GetValueOrDefault(),
FeedbackReplies = c.Replies.Select(r => new FeedbackReply
{
Id = r.Id,
UserDisplayName = r.Author.DisplayName,
ReplyText = r.Content,
DateCreated = r.CreatedTime.GetValueOrDefault(),
FeedbackCommentId = c.Id
}).ToList()
}).ToList();
_context.SaveChanges();
foreach (FeedbackComment c in feedbackComments)
{
if (!_context.FeedbackComments.Any(fc => fc.Id == c.Id))
{
ApplicationUser commentOwner = _context.ApplicationUsers.FirstOrDefault(au => au.GoogleDisplayName == c.UserDisplayName);
if(commentOwner != null)
{
c.UserId = commentOwner.Id;
_context.FeedbackComments.Add(c);
newComments = true;
_context.SaveChanges();
}
}
foreach (FeedbackReply r in c.FeedbackReplies)
{
if (!_context.FeedbackReplies.Any(fr => fr.Id == r.Id))
{
ApplicationUser replyOwner = _context.ApplicationUsers.FirstOrDefault(au => au.GoogleDisplayName == c.UserDisplayName);
if (replyOwner != null)
{
r.UserId = replyOwner.Id;
_context.FeedbackReplies.Add(r);
newComments = true;
_context.SaveChanges();
}
}
}
}