using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace Core.Common
{
    public abstract class GenericRepository<T> : IGenericRepository<T>
                                                    where T : class
    {

        private DbContext context;
        private DbSet<T> entitySet;



        public DbContext Context
        {
            get { return context; }
        }

        public GenericRepository(DbContext context)
        {
            this.context = context;
            entitySet = context.Set<T>();
        }

        public virtual void Add(T entity)
        {
            entitySet.Add(entity);
        }

        public T GetById(int id)
        {
            return (entitySet.Find(id));
        }

        public void Update(int id)
        {
            var entity = GetById(id);
            context.Entry(entity).State = EntityState.Modified;
        }

        public virtual void Delete(int id)
        {
            var entity = GetById(id);
            entitySet.Remove(entity);
        }



        public virtual IQueryable<T> GetAll()
        {

            IQueryable<T> query = entitySet;
            return query;
        }

        public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            IQueryable<T> query = entitySet.Where(predicate);
            return query;
        }

  
        public virtual void Save()
        {
            context.SaveChanges();
        }

        public void Dispose()
        {
            context.Dispose();
        }
    }
}
