| by Achyut Kendre | No comments

Generic Repository

Repository Pattern

In last post we use simple repository pattern.In simple repository when we add more and more repositories we end up with writing same code again and specially core for CURD operations. If you add more domain entities you need to write same code again and again to perform the CURD operations for various repositories. Only difference is entity class, when we work with customer repository it works with customer object, when we do it for emp, it works with emp object.

Solution is generic feature of C#. Generic allow us to implement the classes and methods those are data type independent. So we need to create the generic repository.

1.Create generic interface with name IGeneric –

 public interface IGeneric <T>
    {
        void Add(T rec);
        void Edit(T rec);
        void Delete(Int64 id);
        List<T> GetAll();
        T FindById(Int64 id);
    }

2.Create generic repository class called GenericRepo implement IGeneric as follows –

 public class GenericRepo<T> : IGeneric<T> where T:class
    {
        DbContext db;
        public GenericRepo()
        {
            db = new CompanyContext();
        }
        public void Add(T rec)
        {
            db.Set<T>().Add(rec);
            db.SaveChanges();
        }

        public void Delete(long id)
        {
            T rec = db.Set<T>().Find(id);
            db.Set<T>().Remove(rec);
            db.SaveChanges();
        }

        public void Edit(T rec)
        {
            db.Entry(rec).State = EntityState.Modified;
            db.SaveChanges();
        }

        public T FindById(long id)
        {
            return db.Set<T>().Find(id);
        }

        public List<T> GetAll()
        {
            return db.Set<T>().ToList();
        }
    }

3. Inherit your repository classes from the Generic Repositories to get that common set of operations as follows –

public class CustomerRepo :GenericRepo<Customer>,ICustomer
    {
        //contain actual data access code to work with customer entity
        CompanyContext cc;
        public CustomerRepo()
        {
            cc = new CompanyContext();
        }
  // implement repository specific methods here. 
    }

4. Do not need to modify the web project just run the web project.