Author - StudySection Post Views - 408 views
Repository

Repository Pattern in C#

A repository design pattern is basically the coding standard that separates the data access logic and maps it to the entities in the business logic. i.e. It introduces a middle layer to communicate with databases.

Earlier, we used to access our database directly, without using any middle Layer or Data Access Layer.

It mediates between the domain and the data mapping layers using an interface for accessing the domain objects. In this, the entities, the data access logic, and the business logic talk to each other using interfaces. It hides the details of data access from the business logic.

Business logic is not aware of what the application is using i.e. whether it is using LINQ to SQL or ADO.NET. In the future, we can change the data sources or architecture without affecting the business logic. It is basically centralizing the data access logic, so as to make code maintainability easier.

How to implement?

To implement this :

  • Firstly we will create one Interface class. Name of interface Class can be I+ “Name you wanna pick”/Student + Repository = IStudentRepository.cs
  • Now create a Repository class (StudentRepository.cs) that will extend the interface created above and implement all methods defined in the interface class. In the repository class, we will write only database operations. i.e.If we want to Add/Delete/Update some data in the database then we will write respective logic in respective methods(Add/Update or Delete Methods).
  • Now go to controller.cs class and create an object of the Student Repository class by calling the constructor of the repository in the constructor of the controller.
    Eg:- HomeController is the class that is calling the StudentRepository constructor from its own constructor. This is to access all the methods of the repository.
    C-Repository
  • Now we can call any method of the StudentRepository like shown below:
    Calling the InsertStudent() & SaveChanges() methods, implemented in the Student Repository.
    C-Repository1

Note:- See, This makes the things loosely coupled as well as reusable as we can create a single instance of the Student repository in any class and access the methods.Because the methods in the repository are only to deal with the database & there is no business logic implemented. So, we can reuse the repository methods and further add our logic in different layers/classes as per our requirements without implementing any data access method again.

Knowledge of .NET is quite rewarding in the IT industry. If you have got some skills in the .NET framework then a .NET Certification Exams from StudySection can prove to be a good attachment with your resume. You can go for a foundation level certificate as well as an advanced level certificate in the .NET framework.

Leave a Reply

Your email address will not be published.