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 :

UnitOfWork_2

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

REPLACE in SQL Server

REPLACE function in SQL is used to replace all the occurrences of a specified string, in a given string. It’s syntax is

REPLACE(existing_string, string_to_replace, replacement_string)

Here,

  • existing_string is the string in which we would like to replace all the occurrences specific string. This could be any column of an existing table also.
  • string_to_replace is the string, of which, all the occurrences are to be replaced in the existing string.
  • replacement_string is the new string that we would like to be replaced in place of string_to_replace.

Let’s use a simple example to discuss this concept now. See the commands below :

Replace in SQL Server

We have declared a simple string and applied the replace function, to replace all the occurrences of ‘Test’ with ‘updated’. It will simply REPLACE all the occurrences of ‘Test’ in the existing string. Similarly we could have used any table column in the Select statement above.

STUFF vs REPLACE

It might sound quite similar to the stuff function but they are different. Stuff can be only used to replace a particular string in our existing string. But, replace will replace all the occurrences of a string, in the existing string. Also, stuff may or may not replace any characters in the string, but replace will always replace the specified characters in the string. In other words, stuff can play the role of insertion and replacement in a string, but replace will always play the role of replacement in a string.

Posted in SQL Server | Tagged | Leave a comment