UnitOfWork and Entity Framework Code First

(ASP.NET MVC)


Hi,

I got an opportunity to work with UnitOfWork and repository pattern, The purpose of UnitOfWork is to create dbContext object and all the repository object instances in one place. I had written unit test cases as well using the mock library. I am sharing project/code in this article

Tools required:

1. VISUAL STUDIO 2012 EXPRESS

2. Entity Framework Code First  version 6.0(Nuget Packages)

3. Moq Library (Nuget Packages)

1.UnitOfWork.cs

The unitofwork class initializes the student repository and course repository object using the generic repository instances.

public class UnitOfWork:IUnitOfWork,IDisposable
{
private SchoolDb context = new SchoolDb();
private GenericRepository<Student> studentRepository;
private GenericRepository<Course> courseRepository;

/// <summary>
/// Gets the GenericRepository instance of type student
/// </summary>
public virtual GenericRepository<Student> StudentRepository
{
get
{
if (this.studentRepository == null)
this.studentRepository = new GenericRepository<Student>(context);

return studentRepository;
}
}

/// <summary>
/// Gets the GenericRepository instance of type course
/// </summary>

public virtual GenericRepository<Course> CourseRepository
{
get
{
if (this.courseRepository == null)
this.courseRepository = new GenericRepository<Course>(context);

return courseRepository;
}
}

/// <summary>
/// Save the db context changes
/// </summary>
public void Save()
{
context.SaveChanges();
}

private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}

/// <summary>
/// Free the context resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}

2.GenericRepository.cs

The generic repository class is used by the unitofwork class to create the repository objects.

public class GenericRepository<TEntity> where TEntity : class
{
internal SchoolDb context;
internal DbSet<TEntity> dbSet;

public GenericRepository()
{

}

public GenericRepository(SchoolDb context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}

public virtual IEnumerable<TEntity> GetList()
{
IQueryable<TEntity> query = dbSet;

return query.ToList();
}
}

3.Student Repository

The student repository is used in this example

public class StudentRepository:IStudentRepository,IDisposable
{
private SchoolDb context;

/// <summary>
/// initialize the dbcontext
/// </summary>
/// <param name="context"></param>
public StudentRepository(SchoolDb context)
{
this.context = context;
}

/// <summary>
/// Gets the students list
/// </summary>
/// <returns></returns>
public virtual IEnumerable<Models.Student> GetStudents()
{
return context.Students.ToList();
}

/// <summary>
/// Save the context changes
/// </summary>
public void Save()
{
context.SaveChanges();
}

private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}

/// <summary>
/// Free context resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}

4.School Controller

The school controller class which creates the object of the unitofwork to invoke the studentrepository and courserepository to get its corressponding list.

public class SchoolController : Controller
{
private UnitOfWork unitOfWork;

/// <summary>
/// Initialize the unitofwork instance
/// </summary>
/// <param name="unitOfWork"></param>
public SchoolController(UnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}

/// <summary>
/// Gets the students list
/// </summary>
/// <returns></returns>
public ActionResult GetStudents()
{
return View(unitOfWork.StudentRepository.GetList());
}

/// <summary>
/// Gets the courses list
/// </summary>
/// <returns></returns>
public ActionResult GetCourses()
{
return View(unitOfWork.CourseRepository.GetList());
}

public ActionResult TryItOut()
{
return View();
}
}


5. Unit Test Cases

The unit test cases are written using the moq library for the bot StudentRepository and CourseRepository.

[TestClass]
public class SchoolControllerTest
{
/// <summary>
/// Test case for testing students list
/// </summary>
[TestMethod]
public void IsStudentsNull()
{
//Arrange
//Creating students list
var students = new List<Student>
{
new Student
{
StudentID = 1,
LastName = "Prasad",
FirstName = "Giri",
HireDate = DateTime.Now.AddDays(1),
EnrollmentDateTime = DateTime.Now.AddDays(-1)
},
new Student
{
StudentID = 2,
LastName = "Stewart",
FirstName = "Jasmine",
HireDate = DateTime.Now.AddDays(2),
EnrollmentDateTime = DateTime.Now.AddDays(-2)
},
new Student
{
StudentID = 3,
LastName = "White",
FirstName = "Anthony",
HireDate = DateTime.Now.AddDays(3),
EnrollmentDateTime = DateTime.Now.AddDays(-3)
},
}.AsQueryable();

//Act
//Creating mock object for student repository
Mock<UnitOfWork> mockContext = new Mock<UnitOfWork>();
mockContext.Setup(s => s.StudentRepository.GetList()).Returns(students);


SchoolController controller = new SchoolController(mockContext.Object);
ViewResult result = controller.GetStudents() as ViewResult;
//Assert
//Testing students list is null or not
Assert.IsNotNull(result.Model);
}

/// <summary>
/// Test case for testing course list
/// </summary>
[TestMethod]
public void IsCoursesNull()
{
//Arrange
//Creating course list
var courses = new List<Course>
{
new Course {Id = 1, Name = "Computer Science"},
new Course {Id = 2, Name = "Biology"},
new Course {Id = 3, Name = "Maths"},
}.AsQueryable();

//Act
//Creating mock object for course repository
Mock<UnitOfWork> mock = new Mock<UnitOfWork>();
mock.Setup(c => c.CourseRepository.GetList()).Returns(courses);

SchoolController controller = new SchoolController(mock.Object);
ViewResult result = controller.GetCourses() as ViewResult;

//Assert
//Testing course list is null or not
Assert.IsNotNull(result.Model);
}

}


Ratings


Average Rating: 5.00 by 4 users
Giri Prasad
5/18/2015
5/18/2015
Download PDF
Download Project

Comments