CreateUser function assumes the data being delivered via parameters are clean and gets called or initiated from the Business Manager (another class). This function is responsible to do the following things:
- Fetch the Connection String
- Open the database connection
- Start the transaction
- Inserts a user record
- Loop through User Role entity list and Insert all the records
- Commits the transaction
- Finally or Catch Code block gets executed
I would like to identify is this a correct way of implementing Unit of Work pattern? Is there any catch in my implementation? Comments are written through out the code. By the way, am not using Entity Framework (using Dapper) and don't have an intention to use it.
using System;
using System.Collections.Generic;
using System.Data;
using Application.Entities.Interfaces;
using Dapper;
namespace Application.DataStore.UnitOfWork
{
public class UserUnitOfWork
{
private IDbConnection connection;
private IDbTransaction transaction;
#region CreateTenant
public void CreateUser(IUserEntity userEntity, IEnumerable<IUsersUserRoleEntity> usersUserRoleListEntity)
{
try
{
//fetching the connection string from the config file.
this.connection = new DbConnectionHelper.DbConnectionHelper().GetDbConnection();
//open the connection
this.connection.Open();
//start the transaction
this.transaction = this.connection.BeginTransaction();
//insert into user table
int? userId = this.connection.Insert(userEntity, transaction);
//multiple inserts in a loop for user roles
foreach (var userRole in usersUserRoleListEntity)
{
//assign UserId before the insert
userRole.UserId = userId.Value;
//insert into user role table
this.connection.Insert(userRole, transaction);
}
//commit
this.transaction.Commit();
}
catch (Exception ex)
{
this.transaction.Rollback();
throw ex;
}
finally
{
this.transaction.Dispose(); //Transaction dispose
this.transaction = null;
this.connection.Close();
this.connection.Dispose();
this.connection = null;
}
}
#endregion
}
}