Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. using System;
  2. using System.Data;
  3. using System.Data.Entity;
  4. using System.Data.Entity.Infrastructure;
  5. using System.Linq;
  6.  
  7. public class GenericRepository<T> : IRepository<T>, IDisposable where T : class
  8. {
  9. public GenericRepository(IDbContext context)
  10. {
  11. if (context == null)
  12. {
  13. throw new ArgumentException("An instance of DbContext is " +
  14. "required to use this repository.", "context");
  15. }
  16.  
  17. Context = context;
  18. DbSet = Context.Set<T>();
  19. }
  20.  
  21. protected IDbSet<T> DbSet { get; set; }
  22. protected IDbContext Context { get; set; }
  23.  
  24. public virtual void Dispose()
  25. {
  26.  
  27. }
  28.  
  29. public virtual IQueryable<T> GetAll()
  30. {
  31. return DbSet;
  32. }
  33.  
  34. public virtual IQueryable<T> GetAll(string include)
  35. {
  36. return DbSet.Include(include);
  37. }
  38.  
  39. public virtual T GetById(dynamic id)
  40. {
  41. return DbSet.Find(id);
  42. }
  43.  
  44. public virtual void Add(T entity)
  45. {
  46. var entry = Context.Entry(entity);
  47.  
  48. if (entry.State != EntityState.Detached)
  49. {
  50. entry.State = EntityState.Added;
  51. }
  52. else
  53. {
  54. DbSet.Add(entity);
  55. }
  56.  
  57. Context.SaveChanges();
  58. }
  59.  
  60. public virtual void Update(T entity)
  61. {
  62. DbEntityEntry<T> entry = Context.Entry(entity);
  63. entry.State = EntityState.Modified;
  64. Context.SaveChanges();
  65. }
  66.  
  67. public virtual void Delete(T entity)
  68. {
  69. DbEntityEntry<T> entry = Context.Entry(entity);
  70.  
  71. if (entry.State != EntityState.Deleted)
  72. {
  73. entry.State = EntityState.Deleted;
  74. }
  75. else
  76. {
  77. DbSet.Attach(entity);
  78. DbSet.Remove(entity);
  79. }
  80.  
  81. Context.SaveChanges();
  82. }
  83.  
  84. public virtual void Delete(dynamic id)
  85. {
  86. T entity = GetById(id);
  87.  
  88. if (entity != null)
  89. {
  90. Delete(entity);
  91. }
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement