Newer
Older
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tsi1.BusinessLayer.Dtos;
using Tsi1.BusinessLayer.Helpers;
using Tsi1.BusinessLayer.Interfaces;
using Tsi1.DataLayer;
using Tsi1.DataLayer.Entities;
namespace Tsi1.BusinessLayer.Services
{
public class CourseService : ICourseService
{
private readonly Tsi1Context _context;
private readonly IMapper _mapper;
public CourseService(Tsi1Context context, IMapper mapper)
}
public async Task<ServiceResult<Course>> Create(CourseCreateDto newCourse)
{
var result = new ServiceResult<Course>();
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
result.HasError = true;
result.Message = string.Format(ErrorMessages.DuplicateCourseName, newCourse.Name);
return result;
}
result.Data = course;
return result;
}
public async Task<ServiceResult<List<CoursePreviewDto>>> GetCoursePreviews(string userType, int tenantId)
{
var result = new ServiceResult<List<CoursePreviewDto>>();
var courses = new List<Course>();
if (userType == UserTypes.Student)
{
courses = await _context.StudentCourses
.Include(x => x.Course)
.Select(x => x.Course)
.ToListAsync();
}
else if (userType == UserTypes.Professor)
{
courses = await _context.ProfessorCourses
.Include(x => x.Course)
.Select(x => x.Course)
.ToListAsync();
}
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
public async Task<ServiceResult<bool>> Matriculate(int userId, int courseId)
{
var result = new ServiceResult<bool>();
var user = await _context.Users
.Include(x => x.Student)
.FirstOrDefaultAsync(x => x.Id == userId);
if (user == null || user.Student == null)
{
result.HasError = true;
result.Message = string.Format(ErrorMessages.UserDoesNotExist, userId);
return result;
}
var course = await _context.Courses.FirstOrDefaultAsync(x => x.Id == courseId);
if (course == null)
{
result.HasError = true;
result.Message = string.Format(ErrorMessages.CourseDoesNotExist, courseId);
return result;
}
var studentCourse = new StudentCourse
{
CourseId = courseId,
StudentId = user.Student.Id
};
_context.StudentCourses.Add(studentCourse);
await _context.SaveChangesAsync();
return result;
}