🐛 Trying to fix poll update, again...
This commit is contained in:
@@ -175,6 +175,9 @@ public class PollController(AppDatabase db, PollService polls, PublisherService
|
|||||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||||
var accountId = Guid.Parse(currentUser.Id);
|
var accountId = Guid.Parse(currentUser.Id);
|
||||||
|
|
||||||
|
// Start a transaction
|
||||||
|
await using var transaction = await db.Database.BeginTransactionAsync();
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var poll = await db.Polls
|
var poll = await db.Polls
|
||||||
@@ -192,26 +195,38 @@ public class PollController(AppDatabase db, PollService polls, PublisherService
|
|||||||
if (request.Description != null) poll.Description = request.Description;
|
if (request.Description != null) poll.Description = request.Description;
|
||||||
if (request.EndedAt.HasValue) poll.EndedAt = request.EndedAt;
|
if (request.EndedAt.HasValue) poll.EndedAt = request.EndedAt;
|
||||||
|
|
||||||
|
db.Update(poll);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
// Update questions if provided
|
// Update questions if provided
|
||||||
if (request.Questions != null)
|
if (request.Questions != null)
|
||||||
{
|
{
|
||||||
var newQuestions = request.Questions.Select(q => q.ToQuestion()).ToList();
|
await db.PollQuestions
|
||||||
db.AttachRange(newQuestions);
|
.Where(p => p.PollId == poll.Id)
|
||||||
// Remove existing questions
|
.ExecuteDeleteAsync();
|
||||||
poll.Questions.Clear();
|
var newQuestions = request.Questions
|
||||||
// Add new questions
|
.Select(q => q.ToQuestion())
|
||||||
poll.Questions.AddRange(newQuestions);
|
.Select(q =>
|
||||||
|
{
|
||||||
|
q.PollId = poll.Id;
|
||||||
|
return q;
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
db.PollQuestions.AddRange(newQuestions);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
poll.Questions = newQuestions;
|
||||||
}
|
}
|
||||||
|
|
||||||
polls.ValidatePoll(poll);
|
polls.ValidatePoll(poll);
|
||||||
|
|
||||||
db.Update(poll);
|
// Commit the transaction if all operations succeed
|
||||||
await db.SaveChangesAsync();
|
await transaction.CommitAsync();
|
||||||
|
|
||||||
return Ok(poll);
|
return Ok(poll);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
await transaction.RollbackAsync();
|
||||||
return BadRequest(ex.Message);
|
return BadRequest(ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user