PageRenderTime 39ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Gradebook.Data/Repositories/AccountRepository.cs

https://bitbucket.org/academium/gradebook
C# | 96 lines | 79 code | 17 blank | 0 comment | 9 complexity | c7b6a3d424c10af1e01452d2306deb5a MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.Linq;
  5. using Gradebook.Contracts.Repositories;
  6. using Gradebook.Model;
  7. namespace Gradebook.Data.Repositories
  8. {
  9. public class AccountRepository : Repository<User>, IAccountRepository
  10. {
  11. public AccountRepository(DbContext context) : base(context) { }
  12. public override User Read(int id)
  13. {
  14. if (!Contains(id))
  15. throw new ArgumentException("id");
  16. return DbSet.Include(x => x.Teacher).Single(x => x.Id == id);
  17. }
  18. public User Create(string name, string password, string email)
  19. {
  20. return Create(name, password, email, UserRole.Teacher);
  21. }
  22. public User Create(string name, string password, string email, UserRole role)
  23. {
  24. var user = new User
  25. {
  26. Name = name,
  27. Password = password,
  28. Email = email,
  29. Role = role
  30. };
  31. Create(user);
  32. return user;
  33. }
  34. public User GetUserByName(string username)
  35. {
  36. if (!Contains(username))
  37. throw new ArgumentException("username");
  38. return DbSet.Include(x => x.Teacher).Single(x => x.Name == username);
  39. }
  40. public IEnumerable<User> GetAll(string roleName)
  41. {
  42. var role = ToRole(roleName);
  43. return DbSet.Where(x => x.Role == role);
  44. }
  45. public bool Contains(string userName)
  46. {
  47. return DbSet.Any(x => x.Name == userName);
  48. }
  49. public static UserRole ToRole(string roleName)
  50. {
  51. UserRole role;
  52. if (!Enum.TryParse(roleName, out role)) throw new ArgumentException("roleName");
  53. return role;
  54. }
  55. #region Implementation of IUnitOfWork
  56. public void Commit()
  57. {
  58. DbContext.SaveChanges();
  59. }
  60. private bool _disposed = false;
  61. protected virtual void Dispose(bool disposing)
  62. {
  63. if (!_disposed)
  64. {
  65. if (disposing)
  66. {
  67. DbContext.Dispose();
  68. }
  69. }
  70. _disposed = true;
  71. }
  72. public void Dispose()
  73. {
  74. Dispose(true);
  75. GC.SuppressFinalize(this);
  76. }
  77. #endregion
  78. }
  79. }