| by Achyut Kendre | No comments

Repository Design Pattern – simple implementation

Repository Pattern
Repository Pattern

What is Repository Pattern?

  • Repositories are classes or components that encapsulate the logic required to access data sources.
  • They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.
  • This lets you focus on the data persistence logic rather than on data access plumbing.

Advantages Repository Pattern

  • Your business logic can be unit tested without data access logic;
  • The database access code can be reused;
  • Your database access code is centrally managed so easy to implement any database access policies, like caching;
  • It’s easy to implement domain logic;
  • Your domain entities or business entities are strongly typed with annotations; and more.

Project Structure for Demo

It is not necessary to create the similar project structure inside your application, but we are going to use DI and Unit Of work pattern so we are creating following project structure. Create following projects –

  • Core / Entities/ Domain
  • Infra/ Services/ Persistence
  • Web Application
ProjectDescriptionType
Core/Entities/DomainIt will contain set of domain classes /Model classes and their meta data that is used to map or capture data. Class Library Type
Infra/Services/PersistenceHere we will create the interfaces who list out the set of operations that you want to perform with domain model or entities classes. Here we will also create the repository classes to implement those operations using entity framework. Class Library Type
Web/Winform/WPFThis will be client project who will use the core and infra projects. using dependency injectionsWe will create ASP.NET MVC project.

Steps to Implement this –

  1. Create a empty solution with a name Company
  2. Add a class library .NET Framework project with a name Company.Core
  3. Implement a class Customer as follows, use data annotations to define some meta data for data annotations add the reference of System.ComponentModel.DataAnnotation.
 [Table("CustomerTbl")]
    public class Customer
    {
        [Key]
        public Int64 CustomerID { get; set; }
        public string CustomeName { get; set; }
        public string EmailID { get; set; }
        public string Address { get; set; }
        public string MobileNo { get; set; }
        public decimal CreditLimit { get; set; }
    }
  1. Add class library type of project called Company.Infra to your blank solution.
  2. Install entity framework using nuget package manager console and following command –
    Install-Package EntityFramework
  3. Reference the core project from infra using references
  4. Create Company context class as follows with dbset type of property in company context class as follows.
 public class CompanyContext:DbContext
    {
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Emp> Emps { get; set; }
    }

8. Define a connection string as follows in app.config file of infra project.

 <add name="CompanyContext" connectionString="Data Source=servername;Initial Catalog=databasename;Integrated Security=true;" providerName="System.Data.SqlClient" />

9. Create folder called interfaces and add the interface with name ICustomer with following set of interfaces.

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

10. Create a folder called repositories and create a class called customer repository where implement these set of of methods using entity framework as follows –

public class CustomerRepo : ICustomer
    {
        //contain actual data access code to work with customer entity
        CompanyContext cc;
        public CustomerRepo()
        {
            cc = new CompanyContext();
        }
        public void Add(Customer rec)
        {
            cc.Customers.Add(rec);
            cc.SaveChanges();
        }
        public void Delete(long id)
        {
            Customer rec = cc.Customers.Find(id);
            cc.Customers.Remove(rec);
        }
        public void Edit(Customer rec)
        {
            cc.Entry(rec).State = System.Data.Entity.EntityState.Modified;
            cc.SaveChanges();
        }
        public Customer FindById(long id)
        {
            return cc.Customers.Find(id);
        }
        public List<Customer> GetAll()
        {
            return cc.Customers.ToList();
        }
    }

No w your repository is ready.

  1. in next step add a asp.net web application .net framework to same solution,reference core and infra project.
  2. create a custcontroller and create customer repository instance to get, credit, edit ,delete customer data.
  3. also create required views.
 public class CustomerRepo : ICustomer
    {
        //contain actual data access code to work with customer entity
        CompanyContext cc;
        public CustomerRepo()
        {
            cc = new CompanyContext();
        }
        public void Add(Customer rec)
        {
            cc.Customers.Add(rec);
            cc.SaveChanges();
        }

        public void Delete(long id)
        {
            Customer rec = cc.Customers.Find(id);
            cc.Customers.Remove(rec);
        }

        public void Edit(Customer rec)
        {
            cc.Entry(rec).State = System.Data.Entity.EntityState.Modified;
            cc.SaveChanges();
        }

        public Customer FindById(long id)
        {
            return cc.Customers.Find(id);
        }

        public List<Customer> GetAll()
        {
            return cc.Customers.ToList();
        }
    }
  1. If you get error regarding the System.Data.SqlClient provider please add the reference to these two files –
    EntityFramework.SqlServer.dll and EntityFramework.dll in the web project.
  2. Run the project or application.