Files
TechHelper/TechHelper.Server/Repository/ExamRepository.cs

97 lines
3.0 KiB
C#

using Entities.Contracts;
using Entities.DTO;
using Microsoft.EntityFrameworkCore;
using SharedDATA.Api;
namespace TechHelper.Server.Repository
{
public class ExamRepository : IExamRepository
{
private readonly IUnitOfWork _unitOfWork;
private readonly IRepository<Assignment> _assignmentRepo;
private readonly IRepository<AssignmentGroup> _assignmentGroupRepo;
private readonly IRepository<QuestionGroup> _questionGroupRepo;
private readonly IRepository<Question> _questionRepo;
public ExamRepository(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_assignmentRepo = _unitOfWork.GetRepository<Assignment>();
_assignmentGroupRepo = _unitOfWork.GetRepository<AssignmentGroup>();
}
public async Task<Assignment?> GetFullExamByIdAsync(Guid assignmentId)
{
var assignment = await _assignmentRepo.GetFirstOrDefaultAsync(
predicate: a => a.Id == assignmentId && !a.IsDeleted,
include: source => source
.Include
(a => a.AssignmentGroups.Where(ag => ag.ParentGroup == null && !ag.IsDeleted)) // 加载根题组
.ThenInclude(ag => ag.ChildAssignmentGroups.Where(cag => !cag.IsDeleted)) // 加载子题组
.ThenInclude(cag => cag.AssignmentQuestions.Where(aq => !aq.IsDeleted)) // 加载子题组的题目
.ThenInclude(aq => aq.Question)
.Include(a => a.AssignmentGroups.Where(ag => ag.ParentGroup == null && !ag.IsDeleted)) // 再次从根开始,加载题组下的题目
.ThenInclude(ag => ag.AssignmentQuestions.Where(aq => !aq.IsDeleted))
.ThenInclude(aq => aq.Question)
);
if (assignment?.AssignmentGroups != null)
{
foreach (var rootGroup in assignment.AssignmentGroups)
{
await LoadSubGroupsRecursive(rootGroup);
}
}
return assignment;
}
private async Task LoadSubGroupsRecursive(AssignmentGroup group)
{
// EF Core 已经加载了下一层,我们需要确保更深层次的加载
var groupWithChildren = await _assignmentGroupRepo.GetFirstOrDefaultAsync(
predicate: g => g.Id == group.Id,
include: source => source
.Include(g => g.ChildAssignmentGroups.Where(cg => !cg.IsDeleted))
.ThenInclude(cg => cg.AssignmentQuestions.Where(aq => !aq.IsDeleted))
.ThenInclude(aq => aq.Question)
.Include(g => g.AssignmentQuestions.Where(aq => !aq.IsDeleted))
.ThenInclude(aq => aq.Question)
);
group.ChildAssignmentGroups = groupWithChildren.ChildAssignmentGroups;
group.AssignmentQuestions = groupWithChildren.AssignmentQuestions;
if (group.ChildAssignmentGroups != null)
{
foreach (var child in group.ChildAssignmentGroups)
{
await LoadSubGroupsRecursive(child);
}
}
}
public async Task<IEnumerable<Assignment>> GetExamPreviewsByUserAsync(Guid userId)
{
return await _assignmentRepo.GetAllAsync(
predicate: a => a.CreatedBy == userId && !a.IsDeleted);
}
public async Task AddAsync(Assignment assignment)
{
await _assignmentRepo.InsertAsync(assignment);
}
public async Task AddAsync(QuestionGroupDto qg)
{
if(qg.ValidQuestionGroup)
{
}
}
}
}