Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. using Microsoft.EntityFrameworkCore;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4.  
  5. namespace MyMDB.Data.EFCore
  6. {
  7. public abstract class EfCoreRepository<TEntity, TContext> : IRepository<TEntity>
  8. where TEntity : class, IEntity
  9. where TContext : DbContext
  10. {
  11. private readonly TContext context;
  12. public EfCoreRepository(TContext context)
  13. {
  14. this.context = context;
  15. }
  16. public async Task<TEntity> Add(TEntity entity)
  17. {
  18. context.Set<TEntity>().Add(entity);
  19. await context.SaveChangesAsync();
  20. return entity;
  21. }
  22.  
  23. public async Task<TEntity> Delete(int id)
  24. {
  25. var entity = await context.Set<TEntity>().FindAsync(id);
  26. if (entity == null)
  27. {
  28. return entity;
  29. }
  30.  
  31. context.Set<TEntity>().Remove(entity);
  32. await context.SaveChangesAsync();
  33.  
  34. return entity;
  35. }
  36.  
  37. public async Task<TEntity> Get(int id)
  38. {
  39. return await context.Set<TEntity>().FindAsync(id);
  40. }
  41.  
  42. public async Task<List<TEntity>> GetAll()
  43. {
  44. return await context.Set<TEntity>().ToListAsync();
  45. }
  46.  
  47. public async Task<TEntity> Update(TEntity entity)
  48. {
  49. context.Entry(entity).State = EntityState.Modified;
  50. await context.SaveChangesAsync();
  51. return entity;
  52. }
  53.  
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement