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

namespace MvpSample.DAL.Contracts
{
    public abstract class GenericRepository<C, T> : IGenericRepository<T>
                                                    where T : class
                                                    where C : DbContext, new()
    {

        private C context = new C();
        public C Context
        {

            get { return context; }
            set { context = value; }
        }

        public virtual void Add(T entity)
        {
            context.Set<T>().Add(entity);
        }

        public T GetById(int id)
        {
            return (context.Set<T>().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);
            context.Set<T>().Remove(entity);
        }



        public virtual IQueryable<T> GetAll()
        {

            IQueryable<T> query = context.Set<T>();
            return query;
        }

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

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

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