Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Data;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Linq;
- public class GenericRepository<T> : IRepository<T>, IDisposable where T : class
- {
- public GenericRepository(IDbContext context)
- {
- if (context == null)
- {
- throw new ArgumentException("An instance of DbContext is " +
- "required to use this repository.", "context");
- }
- Context = context;
- DbSet = Context.Set<T>();
- }
- protected IDbSet<T> DbSet { get; set; }
- protected IDbContext Context { get; set; }
- public virtual void Dispose()
- {
- }
- public virtual IQueryable<T> GetAll()
- {
- return DbSet;
- }
- public virtual IQueryable<T> GetAll(string include)
- {
- return DbSet.Include(include);
- }
- public virtual T GetById(dynamic id)
- {
- return DbSet.Find(id);
- }
- public virtual void Add(T entity)
- {
- var entry = Context.Entry(entity);
- if (entry.State != EntityState.Detached)
- {
- entry.State = EntityState.Added;
- }
- else
- {
- DbSet.Add(entity);
- }
- Context.SaveChanges();
- }
- public virtual void Update(T entity)
- {
- DbEntityEntry<T> entry = Context.Entry(entity);
- entry.State = EntityState.Modified;
- Context.SaveChanges();
- }
- public virtual void Delete(T entity)
- {
- DbEntityEntry<T> entry = Context.Entry(entity);
- if (entry.State != EntityState.Deleted)
- {
- entry.State = EntityState.Deleted;
- }
- else
- {
- DbSet.Attach(entity);
- DbSet.Remove(entity);
- }
- Context.SaveChanges();
- }
- public virtual void Delete(dynamic id)
- {
- T entity = GetById(id);
- if (entity != null)
- {
- Delete(entity);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement