source: iknow-api/Repository/Implementations/UserRepository.cs@ aee2b88

Last change on this file since aee2b88 was aee2b88, checked in by Stefan-Saveski <stefansaveski19@…>, 9 months ago

Upgraded database, added get subjects and get passed subjects.

  • Property mode set to 100644
File size: 3.2 KB
Line 
1using iknow_api.Models;
2using iknow_api.Data;
3using Microsoft.EntityFrameworkCore;
4
5namespace iknow_api.Repositories
6{
7 public class UserRepository : IUserRepository
8 {
9 private readonly AppDbContext _context;
10
11 public UserRepository(AppDbContext context)
12 {
13 _context = context;
14 }
15
16 public async Task<bool> UserExistsAsync(string username)
17 {
18 return await _context.User.AnyAsync(u => u.Email == username);
19 }
20
21 public async Task<User?> GetUserByUsernameAsync(string username)
22 {
23 return await _context.User.FirstOrDefaultAsync(u => u.Email == username);
24 }
25
26 public async Task<User?> GetUserByIdAsync(int id)
27 {
28 return await _context.User
29 .Include(u => u.ContactInfo)
30 .Include(u => u.EnrollmentInfo)
31 .Include(u => u.HighSchool)
32 .FirstOrDefaultAsync(u => u.Id == id);
33 }
34
35
36 public async Task<User?> GetOnlyUserByIdAsync(int id)
37 {
38 return await _context.User.FirstOrDefaultAsync(u => u.Id == id);
39 }
40 public async Task AddUserAsync(User user)
41 {
42 _context.User.Add(user);
43 await _context.SaveChangesAsync();
44 }
45 public async Task AddContactAsync(ContactInfo contactInfo)
46 {
47 _context.ContactInfo.Add(contactInfo);
48 await _context.SaveChangesAsync();
49 }
50 public async Task AddEnrollmentAsync(EnrollmentInfo enrollment)
51 {
52 _context.EnrollmentInfo.Add(enrollment);
53 await _context.SaveChangesAsync();
54 }
55 public async Task AddHighSchoolAsync(HighSchool highSchool)
56 {
57 _context.HighSchool.Add(highSchool);
58 await _context.SaveChangesAsync();
59 }
60
61 public async Task<int> GetUsersCountAsync()
62 {
63 return await _context.User.CountAsync();
64 }
65 public async Task<List<EnrolledSemesters>> GetUserSemestersAsync(int id)
66 {
67 return await _context.EnrolledSemesters
68 .AsNoTracking()
69 .Include(es => es.Major)
70 .Include(es => es.Semester)
71 .Include(es => es.SemesterSubjects)
72 .ThenInclude(ss => ss.Subject)
73 .Include(es => es.SemesterSubjects)
74 .ThenInclude(ss => ss.Professor)
75 .Where(es => es.UserId == id)
76 .AsSplitQuery() // This helps avoid cartesian explosion
77 .ToListAsync();
78 }
79
80 public async Task<List<PassedSubject>> GetUserPassedSubjectsAsync(int id)
81 {
82 return await _context.PassedSubjects
83 .AsNoTracking()
84 .Include(ps => ps.SemesterSubject)
85 .ThenInclude(ss => ss.Subject)
86 .Include(ps => ps.SemesterSubject)
87 .ThenInclude(ss => ss.EnrolledSemester)
88 .ThenInclude(es => es.Semester)
89 .Include(ps => ps.SemesterSubject)
90 .ThenInclude(ss => ss.Professor)
91 .Where(ps => ps.SemesterSubject.UserId == id)
92 .ToListAsync();
93 }
94
95 }
96}
Note: See TracBrowser for help on using the repository browser.