EF Core Add()只将最后一个元素添加到ICollection中



我正在尝试向EF Core 5中的ICollection对象添加一个元素。但名单上只剩下最后一个元素。举个例子,当一个学生提交答案时,我想把他添加到考试参与者(a(中。它正常工作。但当同一个人提交另一项考试时(B(。他上次考试的成绩丢了(A(。

这是我的密码。

ExamController.cs 中的SubmitExam方法

[HttpPost("submit")]
public async Task<ActionResult<GetExamDTO>> SubmitExam(GetExamDTO getExamDTO)
{
var username = User.FindFirst(ClaimTypes.Name).Value;
var user = await _userManager.Users
.Where(u => u.UserName == username)
.Include(u => u.ParticipatedExams)
.ThenInclude(er => er.Exam)
.FirstOrDefaultAsync();
if (user == null)
return Unauthorized("Invalid User");
var exam = await _dbContext.Exams
.Where(e => e.Id == getExamDTO.Id)
.Include(e => e.Creator)
.Include(e => e.Participants)
.Include(exam => exam.Questions)
.ThenInclude(question => question.Options)
.AsSplitQuery()
.SingleOrDefaultAsync();
if (exam == null)
return BadRequest("Invalid Exam Id");
if (!exam.SubmissionEnabled)
return BadRequest("Exam is over. You are too late.");
double marksObtained = 0;
double negativeMarksObtained = 0;
for (int i = 0; i != getExamDTO.Questions.Count(); ++i)
{
var question = exam.Questions.ElementAt(i);
if (question.CorrectAnswerText == getExamDTO.Questions[i].ProvidedAnswer.Text)
{
marksObtained += question.Marks;
}
else
{
marksObtained -= exam.NegativeMarks;
negativeMarksObtained -= exam.NegativeMarks;
}
}
var participatedFromExam = exam.Participants.Where(u => u.Id == user.Id)
.SingleOrDefault();
var participatedFromUser = user.ParticipatedExams
.Where(er => er.ExamId == exam.Id)
.SingleOrDefault();
System.Console.WriteLine("Submit" + participatedFromExam);
if (participatedFromExam == null && participatedFromUser == null) // If user sits for the first time, count him as new.
{
exam.Participants.Add(user); // Participants gets empty for every exam except the last submitted one. It fried my brain.
++exam.Attendees;
if (await _dbContext.SaveChangesAsync() > 0)
System.Console.WriteLine("Added submission");
var result = new ExamResult
{
Exam = exam,
Score = marksObtained
};
user.ParticipatedExams.Add(result);
await _userManager.UpdateAsync(user);
}
var examDto = examToDto(exam);
examDto.Participated = true;
examDto.MarksObtained = marksObtained;
examDto.Questions = getExamDTO.Questions;
examDto.NewSubmission = true;
examDto.NegativeMarks = negativeMarksObtained;
return Ok(examDto);
}

EntityUser.cs

public class EntityUser : IdentityUser
{
public ICollection<ExamResult> ParticipatedExams { get; set; }
public DateTime? LastActive { get; set; } = DateTime.UtcNow;
}

Exam.cs

public class Exam
{
public string Title { get; set; }
public Guid Id { get; set; }
public int Attendees { get; set; } = 0;
public string CreatorId { get; set; }
public EntityUser Creator { get; set; }
public DateTime CreatedAt { get; set; }
public int Duration { get; set; }
public double TotalMarks { get; set; }
public double NegativeMarks { get; set; }
public bool SubmissionEnabled { get; set; }
public ICollection<Question> Questions { get; set; }
public ICollection<EntityUser> Participants { get; set; }
}

ExamResult.cs

public class ExamResult
{
public Guid Id { get; set; }
public Exam Exam { get; set; }
public Guid ExamId { get; set; }
public double Score { get; set; }
}

GetExamDTO.cs

public class GetExamDTO
{
public string Title { get; set; }
public Guid Id { get; set; }
public int Attendees { get; set; } = 0;
public string Subject { get; set; }
public string CreatorId { get; set; }
public string Creator { get; set; }
public DateTime CreatedAt { get; set; }
public int Duration { get; set; }
public double TotalMarks { get; set; }
public double MarksObtained { get; set; }
public double NegativeMarks { get; set; }
public bool SubmissionEnabled { get; set; }
public bool Participated { get; set; }
public bool NewSubmission { get; set; }
public List<QuestionDTO> Questions { get; set; }
public List<ParticipantDTO> Participants { get; set; }
}

我将感谢任何帮助。提前感谢。

通过添加UserId 修复Examresult类

public partial class ExamResult
{
public Guid Id { get; set; }
public int? UserId { get; set; }
public virtual EntityUser User { get; set; }
public Guid ExamId { get; set; }
public virtual Exam Exam { get; set; }

public double Score { get; set; }
}
public partial class EntityUser : IdentityUser
{
public virtual ICollection<ExamResult> ParticipatedExams { get; set; }
public DateTime? LastActive { get; set; } = DateTime.UtcNow;
}

您可以尝试将fluent api添加到数据库上下文中

public virtual DbSet<ExamResult> ExamResults { get; set; }
.....
modelBuilder.Entity<ExamResult>(entity =>
{
entity.HasOne(d => d.User)
.WithMany(p => p.ParticipatedExams)
.HasForeignKey(d => d.UserId);

});

并编码

var result = new ExamResult
{
UserId=user.Id,
ExamId = exam.Id,
Score = marksObtained
};
_dbContext.ExamResults.Add(result)
await _dbContext.SaveChangesAsync();

最新更新