Getting started with Repository pattern using C#

In this article, we will discuss about the repository pattern and will create a simple example to get the basic working of this pattern.

To understand why we should be using this pattern, let’s take example of an MVC application, using the entity framework. As long as we are getting the correct results, we are not concerned with how the application code is structured, what are different layers defined, how they interact, how they pass the required data between them etc. and in most of the cases, we use the database context directly inside the controllers. This creates tight coupling between the controller and the data access layer, and if we closely look into this type of code, it violates the Single Responsibility Principle as well as Open close principle. Any change related to data-access layer can break the controller code. In such a case, our code structure have the following layers :

Repository pattern using C#

As seen from the above structure, layer 1 is directly using the database context and connects with the sql server. This is where the repository pattern can be implemented, to separate the layers. Our aim will be to separate the controller and the data access layer(database context) by using an intermediate layer i.e. repository layer, for communication between the two. So our code structure now changes to the following :

Repository pattern using C#

Example to use Repository pattern using C# :

To implement this pattern, we can either use the approach of having one-repository per model, which means, each entity of the database will have its own repository, or we can use a generic repository, which can be used by all the entities of the database.

For our example, we will be using the generic repository, with database first approach along with entity framework 5.0 and .Net framework 4.0. So let’s start with the example.

What is generic repository ?

A generic repository is a generic class, with basic CRUD methods in it (and of-course other methods can be added as per the need). This class and its member functions can be used for any entity of the database. This means, if we have entities Customers and Orders, this single generic class can be used for both of them.

To start with, we will create a sample database with a table to store the Customer data. We will be creating a simple form in mvc to add basic details in the table we created. Next, we will create a generic repository with our required operations to get all records, add/update/delete records. So our repository would look like the following.

Repository pattern using C#

Here, TEntity is the generic type which can be any entity of the database i.e. it could be Customer or it can be Orders. All the operations will be applied on this TEntity type only.

Next, our task will be to create a generic unit of work class. If you are not aware of the Unit of work in repository pattern, then I would suggest you to read this previous article to get an idea about this. Just to re-iterate about unit of work, it will act as the mediator between the mvc controller and the generic repository, to perform all database transactions in a single go (will discuss later in the article). This is because SaveChanges will be called by the instance of unit of work class, only after it has performed operations for the entities involved. So our generic unit of work code will be like following:

Getting started with Repository pattern using C#

Here, we have a method named GetRepoInstance, which returns an instance of the type GenericRepository<TEntity>, where, TEntity will represents the entity for which we are going to perform the database operations. For example, if we are going to work with Customer entity, it will return instance GenericRepository<Customer> and if we are going to work with Order entity, it will return GenericRepository<Order>. Next we have the SaveChanges method to commit all the database transactions in one go, by the current instance of unit of work we are using.

So we are done with setting up the unit of work class. Now we move in to the controller and will write the code for get/add/update/remove data. Let’s start with the listing of the records. We will discuss the GetAllRecords repository method and on the same lines, rest of the methods will be called by the controller. To start with, we will create the Customer repository instance, via use of the unit of work class. So we instantiate the unit of work class and call GetRepoInstance method to get the instance of the Customer repository. Now, when we call any method of the generic repository, it will call that method for the Customer entity, as it holds the reference to TEntity type at that time. This is because, when we initialized the generic repository, we created a DbSet of the type TEntity, in its constructor. So any type of CRUD operation is performed on the DbSet. See the code below:

Getting started with Repository pattern using C#

And, our controller method to fetch the records will look like the following:

Repository_3That’s it. We are done with the code to get the records. Run the application and see the results. Similarly, we can write the code for the other operations of update/add/delete. Just instantiate the unit of work and get the instance for the entity repository. Call the methods and it’s all we have to do. Rest of our code will look like the following:

Getting started with Repository pattern using C#

Getting started with Repository pattern using C#

Why unit of work ?

Earlier in our article, we discussed a point about the preferred use of unit of work class. The advantage of using this class is the fact that when we are performing multiple operations in one single controller method, we will be committing all the changes in the database by calling the SaveChanges only once and that is through the unit of work instance.
For example, in our above delete method, we might also want to delete the Address related to that Customer(assuming it is in a separate table). In that case, we find the associated address record using the GetFirstOrDefault() method and call the delete operation for it. Finally, we call the SaveChanges. In such a situation, if our first transaction fails, the other one will be also blocked, as the SaveChanges is never executed and thus maintains the database consistency.

So this was a basic article to get started with the repository pattern. Hope you enjoyed reading it…!!!

Posted in Design and Architecture, Design Patterns | Tagged | Leave a comment

Unit of Work in Repository Pattern

Unit of Work is the concept related to the effective implementation of the repository pattern. To understand this concept in better way, it is important to know the concept of repository pattern. We will not get into the details of the repository pattern in this discussion. But a small idea of this concept is necessary to proceed further.

What is Repository pattern ?

A repository is nothing but a class defined for an entity, with all the operations possible on that particular entity. For example, a repository for an entity Customer, will have basic CRUD operations and any other possible operation related to it. A repository pattern can be implemented in following ways :

  • One repository per entity (non generic) : This type of implementation involves the use of one repository class for each entity. For example, if you have two entities Order and Customer, each entity will have its own repository.
  • Generic repository : A generic repository is the one which can be used for all the entities i.e. it can be either used for Order or Customer or any other entity.

What is Unit of Work in Repository pattern ?

Unit of Work is referred to as a single transaction, which involves multiple operations of kind insert/update/delete etc. To say it in simple words, it means that on particular user action(say registration on a website), all the transactions like insert/update/delete etc. are done in one single transaction, rather then doing multiple database transactions. This means, one unit of work here involves insert/update/delete operations, all in one single transaction.

To understand this concept, consider the following implementation of repository pattern using non-generic repository, for a Customer entity.

Unit of Work

The above code seems to be fine. The issue arises when we add repository for another entity, say Order. In that case, both repositories will generate and maintain their own instance of the DbContext. This may lead to issues in future, as each DbContext will have its own in-memory list of changes of the records, of the entities, which are getting added/updated/modified, in a single transaction/operation. In such a case, if the SaveChanges of one of the repository fails and other one succeeds, it will result in database in-consistency. This is where the concept of UnitOfWork comes in the the role.

To avoid this, we will add another layer or intermediate between the controller and the Customer repository. This layer will act as a centralized store for the all repositories to receive the instance of the DbContext. This will make sure that, for a unit of transaction, which spans across multiple repositories, should either complete for all entities or should fail entirely, as all of them will share the same instance of the DbContext. In our above example, while adding data for the Order and Customer entities, in a single transaction, both will use the same DbContext instance. This situation, without and with Unit of work, can be represented like following :

Unit of work in repository pattern

In above representation, during a single operation, which involves Customer & Order entities, both of them use the same DbContext instance. This will make sure that even if one of them breaks, the other one is also not saved, thus maintaining the database consistency. So when SaveChanges is executed, it will be done for both the repositories.

Let us implement this concept in our example. We add a new class called UnitOfWork and this class will receive the instance of the DbContext. The same class will further generate the required repository instances i.e. repository instances for Order & Customer and pass the same DbContext to both the repositories. So our UnitOfWork will be like the following :


And, our Customer Repository will be changed, to receive the instance of DbContext from the unit of work class. See the code below :

Unit of Work in repository pattern

Similarly, we can have the code for the Order repository. Finally, our controller code will be like the following :

Unit of Work in repository pattern

Here, both the Order and Customer repository use the same instance of DbContext and we are executing the save changes using the instance unit of work class. So the changes of a single transaction are either done for both or none. Run the code and see the results.

So this was about the concept of unit of work in repository pattern. Any suggestions are welcome.

Posted in Design and Architecture | Leave a comment

L of S.O.L.I.D. Liskov’s Substitution principle

This is the third in the 5 principles which are defined as an acronym S.O.L.I.D. This principle is further having an acronym called L.S.P. which stands for Liskov’s Substitution Principle. This principle was introduced by Barbara Liskov. A definition from wikipedia about this principle says :

If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).

In simple technical language, it means, when we have a base class and child class relationship, then, if we can successfully replace the object/instance of parent class with object/instance of the child class, without affecting the results which we get with the base class instance, then the two classes conform to this principle. Might sound bit confusing, let’s discuss with an example.

To understand this principle, we will use the same example of the Rectangle-Square hierarchy which you might have seen a lot, where Rectangle is the base class and Square is the derived class. Our discussion focus will be on how the code violates the L.S.P., rather then the actual code is or should have been written for it. The code for this example is below :

Liskov Substitution Principle

And, the client code is :

Liskov Substitution Principle

As per the definition of this principle, if this example does not violates the L.S.P., then the getArea method in the base class will give the same area of a rectangle, i.e. whether we execute this method with the instance of the Rectangle class or the Square class, we should get area as 120. But it is not and this is how it violates L.S.P.

Where is the issue ?

At first, it might seem that the code is fine(until we run it). In-fact, the code will work fine if we attempt to get the area using the instance of the rectangle class. But if we use instance of square class, the result is different. The reason being, when we write

Rectangle _iShape = new Square();

_iShape holds reference of the the type Square. Next, when we execute the setWidth & setHeight methods, it executes the methods of the Square class, which sets height = width (as per the logic of the square has length = breadth) and when the getArea is executed, it calculates incorrect area.

This is the reason that this code violates the Liskov Substitution Principle, when we replaced the object/instance of the Rectangle, with that of Square and this is what this principle is all about i.e.

If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).

So this is about the concept of Liskov Substitution Principle. Hope you enjoyed reading it…!!!

Posted in SOLID Principles | Tagged | Leave a comment

Coaelsce in SQL Server

Coalesce in SQL server basically acts like a Case statement i.e. if value in one of the column is not available then use the value of the second column, and if that is also not available, then use the third column. If none of the column has the value, then null is returned for that value. It’s syntax is :

COALESCE ( expression [ 1...n ] )

Here, expressions 1….n are like possible case statements. Let’s discuss this in detail. Consider the following data in a table :

COALESCE in SQL We have different values of alias names for all the users. But some of them have Alias1, some have Alias2 and some have Alias3. We are required to display alias names based on their availability in the database i.e. if we don’t have Alias1, then display Alias2 and if it is also not available, then use Alias3. This can be easily achieved using COALESCE in the Select statement.

To do this, we simply write the following query with the COALESCE keyword.

SELECT EmpId, EmpName,
COALESCE (Empalias1, empalias2, empalias3) AS AliasName
FROM Employees

Execute the query and see the results.COALESCE in SQL Server

COALESCE acts like case statements and checks if the Alias1 is available or not. If not, then use the Alias2 column and even if that is not available, then use Alias3. This is what happens in the records of Ray, Chris, Jenny and Simi. For Norman, there was no value in any of the alias columns, so it returned null for it.

So this is how we can use the COALESCE in SQL server. Happy coding…!!!

Posted in SQL Server | Tagged | Leave a comment

Friend assemblies in .NET using C#

What is internal access modifier in C# ?

Internal modifier allow to access to the elements of an assembly, within the same assembly only. This means if we have one class library type project with two classes Class1 and Class2, any internal classes in it, will be accessible only within this class library project. When we add reference of it’s dll in any other project, the internal classes of this library will not be accessible in that project.

By default, class is internal in nature.

So, using internal access modifier is like telling our children not to talk with the strangers. We tell our assembly not to share the internal classes with the stranger assemblies.

Access internal members outside the assembly

This was basic about the internal modifier. But suppose we have created a product based library. Now we need to provide access to one of our internal member class to some of our customers and not all of them. Very first thing that will come into our minds is to make the class public. But this will expose the class to all the customers, which they don not even require. Moreover, it results in security vulnerability. This is where the concept of friend assemblies come into the role. We will simply tell our assembly or dll that this class is your friend and you can share your internal members with it. To do this, we just have to add the following line of code on our namespace.

[assembly: InternalsVisibleToAttribute("Name_of_Friend_Class")]

And that’s it. We are done. Build the assembly and we can now access the internal class members as well.

Adding this attribute instructs our assembly to share the details with stranger assemblies. It’s like telling our children name of the people with whom they can talk.

Access internal members of the class outside the assembly – Example

For this, we will create a new project solution and add two project types – one class library named ClassLibrary and other, console application named Consumer. In class library, we add two classes, one as internal named InternalClass and other as public named PublicClass. 

Friend Assembly in .Net

Next, we build this project and add its reference in the Consumer project. Then we try to access these two classes in the console application. We will be able to access the public class but not the internal class.

Friend Assembly in .Net using C#

Now in order to access the internal class in the console application, we add the InternalsVisibleTo attribute, with the name of the assembly in which we would like to access the internal members. In our case, it is named Consumer. See the code below.

Friend Assembly in .Net using C#

Build the code and we can now easily access the internal members. In this way, we can add as many assembly names, as we need.

Friend Assembly in .Net using C#


So this all what we had to do to allow access to internal classes. We can add multiple attributes, with the names of the assemblies with which we would like to share these internal classes. But the condition here is that we need to add this attribute at the namespace level. Hope you enjoyed reading it…!!!

Posted in .Net, C# | Tagged , , | Leave a comment