User1255309776 posted
Hi guys,
I'm creating an online quiz application where many users will take the same exam with multiple choice questions. Users will answer the same questions of the same exam.
I have the following models:
Exam
public class Exam
{
public Exam()
{
Questions = new HashSet<Question>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime ExamDate { get; set; }
public ICollection<Question> Questions { get; set; }
}
Question
public class Question
{
public Question()
{
Answers = new HashSet<Answer>();
}
public int Id { get; set; }
public string Description { get; set; }
public int ExamId { get; set; }
public TimeSpan? Remainedtime { get; set; }
public int Score { get; set; }
public ICollection<Answer> Answers { get; set; }
public ICollection<UserQuestion> UserQuestions { get; set; }
}
Answer
public class Answer
{
public int Id { get; set; }
public string Description { get; set; }
public int QuestionId { get; set; }
public bool Correct { get; set; }
}
User
public class ExamUser: IdentityUser
{
public int Result { get; set; }
public ICollection<UserQuestion> UserQuestions { get; set; }
}
UserQuestion
public class UserQuestion
{
public int ExamUserId { get; set; }
public ExamUser ExamUser { get; set; }
public int QuestionId { get; set; }
public Question Question { get; set; }
}
As you can see, there is many-to-many relation between Examusers and Questions as each user will have say 20 exam questions where each question will get different result for each examuser.
For this I created onmodelcreating which is also must be ok.
public class IntellectDbContext:IdentityDbContext<ExamUser>
{
public IntellectDbContext(DbContextOptions<IntellectDbContext> dbContextOptions) : base(dbContextOptions)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UserQuestion>()
.HasKey(a => new { a.ExamUserId, a.QuestionId });
modelBuilder.Entity<UserQuestion>()
.HasOne(a => a.ExamUser)
.WithMany(b => b.UserQuestions)
.HasForeignKey(a => a.ExamUserId);
modelBuilder.Entity<UserQuestion>()
.HasOne(a => a.Question)
.WithMany(c => c.UserQuestions)
.HasForeignKey(a => a.QuestionId);
}
public DbSet<Answer> Answers { get; set; }
public DbSet<Question> Questions { get; set; }
public DbSet<Exam> Exams { get; set; }
public DbSet<ExamUser> ExamUsers { get; set; }
public DbSet<UserQuestion> UserQuestions { get; set; }
}
The problem is that when calculating result for each user questions, I don't know how to address them in relevant action. I need a correct way of something like this:
public IActionResult QuestionScore()
{
if(_SignInManager.IsSignedIn(User){
foreach(Answer item in Questions){
if(item.Correct) {
//main needed part to fix => UserQuestion.ExamUser.Question.Score = 1; (for ex.)
P.S. Please, ignore minor syntax mistakes.