using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using DAL.Interfaces; namespace DAL.Repositories { public class RepositoryBase where T : class { protected DbContext RepositoryDataContext; protected DbSet RepositoryDbSet; public RepositoryBase(IFoorumDbContext dbContext) { RepositoryDataContext = dbContext as DbContext; if (RepositoryDataContext == null) { throw new ArgumentNullException(paramName: nameof(dbContext)); } RepositoryDbSet = RepositoryDataContext.Set(); if (RepositoryDbSet == null) { throw new NullReferenceException(message: nameof(RepositoryDbSet)); } } public T Add(T entity) { var ret = RepositoryDbSet.Add(entity); SaveChanges(); return ret; } public T Update(T entity) { RepositoryDbSet.Attach(entity); RepositoryDataContext.Entry(entity).State = EntityState.Modified; return entity; } public void Delete(T entity) { RepositoryDbSet.Remove(entity); } public void Delete(Expression> where) { IEnumerable objects = RepositoryDbSet.Where(where).AsEnumerable(); foreach (T obj in objects) RepositoryDbSet.Remove(obj); } public T GetById(int id) { return RepositoryDbSet.Find(id); } public virtual IEnumerable GetAll() { return RepositoryDbSet.ToList(); } public virtual IEnumerable GetMany(Expression> where) { return RepositoryDbSet.Where(where).ToList(); } public T Get(Expression> where) { return RepositoryDbSet.Where(where).FirstOrDefault(); } public int SaveChanges() { return RepositoryDataContext.SaveChanges(); } } }