Advertisement
IvanNikolov2217

vlad 3

May 11th, 2022
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.09 KB | None | 0 0
  1. using BusinessLayer;
  2. using Microsoft.EntityFrameworkCore;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6.  
  7.  
  8. namespace DataLayer
  9. {
  10. public class UserContext : IDB<User,int>
  11. {
  12. GamingDbContext _context;
  13.  
  14. public UserContext(GamingDbContext context)
  15. {
  16. _context = context;
  17. }
  18.  
  19. public void Create(User item)
  20. {
  21. try
  22. {
  23. _context.Users.Add(item);
  24. _context.SaveChanges();
  25. }
  26. catch (Exception ex)
  27. {
  28. throw ex;
  29. }
  30. }
  31.  
  32. public User Read(int key, bool noTracking = false, bool useNavigationProperties = false)
  33. {
  34. try
  35. {
  36. IQueryable<User> query = _context.Users;
  37.  
  38. if (noTracking)
  39. {
  40. query = query.AsNoTrackingWithIdentityResolution();
  41. }
  42.  
  43. if (useNavigationProperties)
  44. {
  45. query = query.Include(u => u.Games).Include(u => u.Friends);
  46. }
  47.  
  48. return query.SingleOrDefault(u => u.ID == key);
  49. }
  50. catch (Exception ex)
  51. {
  52. throw ex;
  53. }
  54. }
  55.  
  56. public IEnumerable<User> Read(int skip, int take, bool useNavigationProperties = false)
  57. {
  58. try
  59. {
  60. IQueryable<User> query = _context.Users.AsNoTrackingWithIdentityResolution();
  61.  
  62. if (useNavigationProperties)
  63. {
  64. query = query.Include(u => u.Games).Include(u => u.Friends);
  65. }
  66.  
  67. return query.Skip(skip).Take(take).ToList();
  68. }
  69. catch (Exception ex)
  70. {
  71. throw ex;
  72. }
  73. }
  74.  
  75. public IEnumerable<User> ReadAll(bool useNavigationProperties = false)
  76. {
  77. try
  78. {
  79. IQueryable<User> query = _context.Users.AsNoTracking();
  80.  
  81. if (useNavigationProperties)
  82. {
  83. query = query.Include(u => u.Games).Include(u => u.Friends);
  84. }
  85.  
  86. return query.ToList();
  87. }
  88. catch (Exception ex)
  89. {
  90. throw ex;
  91. }
  92. }
  93.  
  94. public void Update(User item, bool useNavigationProperties = false)
  95. {
  96. try
  97. {
  98. User userFromDB = Read(item.ID);
  99.  
  100. _context.Entry(userFromDB).CurrentValues.SetValues(item);
  101. _context.SaveChanges();
  102. }
  103. catch (Exception ex)
  104. {
  105. throw ex;
  106. }
  107. }
  108.  
  109. public void Delete(int key)
  110. {
  111. try
  112. {
  113. _context.Users.Remove(Read(key));
  114. _context.SaveChanges();
  115. }
  116. catch (Exception ex)
  117. {
  118. throw ex;
  119. }
  120. }
  121.  
  122. }
  123. }
  124.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement