"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (9 of 10)

by Tom Dykstra

Download Completed Project

The Contoso University sample web application demonstrates how to create ASP.NET MVC 4 applications using the Entity Framework 5 Code First and Visual Studio 2012. For information about the tutorial series, see the first tutorial in the series. You can start the tutorial series from the beginning or download a starter project for this chapter and start here.

[!NOTE]

If you run into a problem you can’t resolve, download the completed chapter and try to reproduce your problem. You can generally find the solution to the problem by comparing your code to the completed code. For some common errors and how to solve them, see Errors and Workarounds.

In the previous tutorial you used inheritance to reduce redundant code in the Student and Instructor entity classes. In this tutorial you’ll see some ways to use the repository and unit of work patterns for CRUD operations. As in the previous tutorial, in this one you’ll change the way your code works with pages you already created rather than creating new pages.

The Repository and Unit of Work Patterns

The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. Implementing these patterns can help insulate your application from changes in the data store and can facilitate automated unit testing or test-driven development (TDD).

In this tutorial you’ll implement a repository class for each entity type. For the Student entity type you’ll create a repository interface and a repository class. When you instantiate the repository in your controller, you’ll use the interface so that the controller will accept a reference to any object that implements the repository interface. When the controller runs under a web server, it receives a repository that works with the Entity Framework. When the controller runs under a unit test class, it receives a repository that works with data stored in a way that you can easily manipulate for testing, such as an in-memory collection.

Later in the tutorial you’ll use multiple repositories and a unit of work class for the Course and Department entity types in the Course controller. The unit of work class coordinates the work of multiple repositories by creating a single database context class shared by all of them. If you wanted to be able to perform automated unit testing, you’d create and use interfaces for these classes in the same way you did for the Student repository. However, to keep the tutorial simple, you’ll create and use these classes without interfaces.

The following illustration shows one way to conceptualize the relationships between the controller and context classes compared to not using the repository or unit of work pattern at all.

Repository_pattern_diagram
Repository_pattern_diagram

You won’t create unit tests in this tutorial series. For an introduction to TDD with an MVC application that uses the repository pattern, see Walkthrough: Using TDD with ASP.NET MVC. For more information about the repository pattern, see the following resources:

[!NOTE] There are many ways to implement the repository and unit of work patterns. You can use repository classes with or without a unit of work class. You can implement a single repository for all entity types, or one for each type. If you implement one for each type, you can use separate classes, a generic base class and derived classes, or an abstract base class and derived classes. You can include business logic in your repository or restrict it to data access logic. You can also build an abstraction layer into your database context class by using IDbSet interfaces there instead of DbSet types for your entity sets. The approach to implementing an abstraction layer shown in this tutorial is one option for you to consider, not a recommendation for all scenarios and environments.

Creating the Student Repository Class

In the DAL folder, create a class file named IStudentRepository.cs and replace the existing code with the following code:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using ContosoUniversity.Models;
   4:   
   5:  namespace ContosoUniversity.DAL
   6:  {
   7:      public interface IStudentRepository : IDisposable
   8:      {
   9:          IEnumerable<Student> GetStudents();
  10:          Student GetStudentByID(int studentId);
  11:          void InsertStudent(Student student);
  12:          void DeleteStudent(int studentID);
  13:          void UpdateStudent(Student student);
  14:          void Save();
  15:      }
  16:  }

This code declares a typical set of CRUD methods, including two read methods — one that returns all Student entities, and one that finds a single Student entity by ID.

In the DAL folder, create a class file named StudentRepository.cs file. Replace the existing code with the following code, which implements the IStudentRepository interface:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Data;
   5:  using ContosoUniversity.Models;
   6:   
   7:  namespace ContosoUniversity.DAL
   8:  {
   9:      public class StudentRepository : IStudentRepository, IDisposable
  10:      {
  11:          private SchoolContext context;
  12:   
  13:          public StudentRepository(SchoolContext context)
  14:          {
  15:              this.context = context;
  16:          }
  17:   
  18:          public IEnumerable<Student> GetStudents()
  19:          {
  20:              return context.Students.ToList();
  21:          }
  22:   
  23:          public Student GetStudentByID(int id)
  24:          {
  25:              return context.Students.Find(id);
  26:          }
  27:   
  28:          public void InsertStudent(Student student)
  29:          {
  30:              context.Students.Add(student);
  31:          }
  32:   
  33:          public void DeleteStudent(int studentID)
  34:          {
  35:              Student student = context.Students.Find(studentID);
  36:              context.Students.Remove(student);
  37:          }
  38:   
  39:          public void UpdateStudent(Student student)
  40:          {
  41:              context.Entry(student).State = EntityState.Modified;
  42:          }
  43:   
  44:          public void Save()
  45:          {
  46:              context.SaveChanges();
  47:          }
  48:   
  49:          private bool disposed = false;
  50:   
  51:          protected virtual void Dispose(bool disposing)
  52:          {
  53:              if (!this.disposed)
  54:              {
  55:                  if (disposing)
  56:                  {
  57:                      context.Dispose();
  58:                  }
  59:              }
  60:              this.disposed = true;
  61:          }
  62:   
  63:          public void Dispose()
  64:          {
  65:              Dispose(true);
  66:              GC.SuppressFinalize(this);
  67:          }
  68:      }
  69:  }

The database context is defined in a class variable, and the constructor expects the calling object to pass in an instance of the context:

[!code-csharpMain]

   1:  private SchoolContext context;
   2:   
   3:  public StudentRepository(SchoolContext context)
   4:  {
   5:      this.context = context;
   6:  }

You could instantiate a new context in the repository, but then if you used multiple repositories in one controller, each would end up with a separate context. Later you’ll use multiple repositories in the Course controller, and you’ll see how a unit of work class can ensure that all repositories use the same context.

The repository implements IDisposable and disposes the database context as you saw earlier in the controller, and its CRUD methods make calls to the database context in the same way that you saw earlier.

Change the Student Controller to Use the Repository

In StudentController.cs, replace the code currently in the class with the following code. The changes are highlighted.

[!code-csharpMain]

   1:  using System;
   2:  using System.Data;
   3:  using System.Linq;
   4:  using System.Web.Mvc;
   5:  using ContosoUniversity.Models;
   6:  using ContosoUniversity.DAL;
   7:  using PagedList;
   8:   
   9:  namespace ContosoUniversity.Controllers
  10:  {
  11:     public class StudentController : Controller
  12:     {
  13:        private IStudentRepository studentRepository;
  14:   
  15:        public StudentController()
  16:        {
  17:           this.studentRepository = new StudentRepository(new SchoolContext());
  18:        }
  19:   
  20:        public StudentController(IStudentRepository studentRepository)
  21:        {
  22:           this.studentRepository = studentRepository;
  23:        }
  24:   
  25:        //
  26:        // GET: /Student/
  27:   
  28:        public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
  29:        {
  30:           ViewBag.CurrentSort = sortOrder;
  31:           ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
  32:           ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
  33:   
  34:           if (searchString != null)
  35:           {
  36:              page = 1;
  37:           }
  38:           else
  39:           {
  40:              searchString = currentFilter;
  41:           }
  42:           ViewBag.CurrentFilter = searchString;
  43:   
  44:           var students = from s in studentRepository.GetStudents()
  45:                          select s;
  46:           if (!String.IsNullOrEmpty(searchString))
  47:           {
  48:              students = students.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper())
  49:                                     || s.FirstMidName.ToUpper().Contains(searchString.ToUpper()));
  50:           }
  51:           switch (sortOrder)
  52:           {
  53:              case "name_desc":
  54:                 students = students.OrderByDescending(s => s.LastName);
  55:                 break;
  56:              case "Date":
  57:                 students = students.OrderBy(s => s.EnrollmentDate);
  58:                 break;
  59:              case "date_desc":
  60:                 students = students.OrderByDescending(s => s.EnrollmentDate);
  61:                 break;
  62:              default:  // Name ascending 
  63:                 students = students.OrderBy(s => s.LastName);
  64:                 break;
  65:           }
  66:   
  67:           int pageSize = 3;
  68:           int pageNumber = (page ?? 1);
  69:           return View(students.ToPagedList(pageNumber, pageSize));
  70:        }
  71:   
  72:        //
  73:        // GET: /Student/Details/5
  74:   
  75:        public ViewResult Details(int id)
  76:        {
  77:           Student student = studentRepository.GetStudentByID(id);
  78:           return View(student);
  79:        }
  80:   
  81:        //
  82:        // GET: /Student/Create
  83:   
  84:        public ActionResult Create()
  85:        {
  86:           return View();
  87:        }
  88:   
  89:        //
  90:        // POST: /Student/Create
  91:   
  92:        [HttpPost]
  93:        [ValidateAntiForgeryToken]
  94:        public ActionResult Create(
  95:           [Bind(Include = "LastName, FirstMidName, EnrollmentDate")]
  96:             Student student)
  97:        {
  98:           try
  99:           {
 100:              if (ModelState.IsValid)
 101:              {
 102:                 studentRepository.InsertStudent(student);
 103:                 studentRepository.Save();
 104:                 return RedirectToAction("Index");
 105:              }
 106:           }
 107:           catch (DataException /* dex */)
 108:           {
 109:              //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
 110:              ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
 111:           }
 112:           return View(student);
 113:        }
 114:   
 115:        //
 116:        // GET: /Student/Edit/5
 117:   
 118:        public ActionResult Edit(int id)
 119:        {
 120:           Student student = studentRepository.GetStudentByID(id);
 121:           return View(student);
 122:        }
 123:   
 124:        //
 125:        // POST: /Student/Edit/5
 126:   
 127:        [HttpPost]
 128:        [ValidateAntiForgeryToken]
 129:        public ActionResult Edit(
 130:           [Bind(Include = "LastName, FirstMidName, EnrollmentDate")]
 131:           Student student)
 132:        {
 133:           try
 134:           {
 135:              if (ModelState.IsValid)
 136:              {
 137:                 studentRepository.UpdateStudent(student);
 138:                 studentRepository.Save();
 139:                 return RedirectToAction("Index");
 140:              }
 141:           }
 142:           catch (DataException /* dex */)
 143:           {
 144:              //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
 145:              ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
 146:           }
 147:           return View(student);
 148:        }
 149:   
 150:        //
 151:        // GET: /Student/Delete/5
 152:   
 153:        public ActionResult Delete(bool? saveChangesError = false, int id = 0)
 154:        {
 155:           if (saveChangesError.GetValueOrDefault())
 156:           {
 157:              ViewBag.ErrorMessage = "Delete failed. Try again, and if the problem persists see your system administrator.";
 158:           }
 159:           Student student = studentRepository.GetStudentByID(id);
 160:           return View(student);
 161:        }
 162:   
 163:        //
 164:        // POST: /Student/Delete/5
 165:   
 166:        [HttpPost]
 167:        [ValidateAntiForgeryToken]
 168:        public ActionResult Delete(int id)
 169:        {
 170:           try
 171:           {
 172:              Student student = studentRepository.GetStudentByID(id);
 173:              studentRepository.DeleteStudent(id);
 174:              studentRepository.Save();
 175:           }
 176:           catch (DataException /* dex */)
 177:           {
 178:              //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
 179:              return RedirectToAction("Delete", new { id = id, saveChangesError = true });
 180:           }
 181:           return RedirectToAction("Index");
 182:        }
 183:   
 184:        protected override void Dispose(bool disposing)
 185:        {
 186:           studentRepository.Dispose();
 187:           base.Dispose(disposing);
 188:        }
 189:     }
 190:  }

The controller now declares a class variable for an object that implements the IStudentRepository interface instead of the context class:

[!code-csharpMain]

   1:  private IStudentRepository studentRepository;

The default (parameterless) constructor creates a new context instance, and an optional constructor allows the caller to pass in a context instance.

[!code-csharpMain]

   1:  public StudentController()
   2:  {
   3:      this.studentRepository = new StudentRepository(new SchoolContext());
   4:  }
   5:   
   6:  public StudentController(IStudentRepository studentRepository)
   7:  {
   8:      this.studentRepository = studentRepository;
   9:  }

(If you were using dependency injection, or DI, you wouldn’t need the default constructor because the DI software would ensure that the correct repository object would always be provided.)

In the CRUD methods, the repository is now called instead of the context:

[!code-csharpMain]

   1:  var students = from s in studentRepository.GetStudents()
   2:                 select s;

[!code-csharpMain]

   1:  Student student = studentRepository.GetStudentByID(id);

[!code-csharpMain]

   1:  studentRepository.InsertStudent(student);
   2:  studentRepository.Save();

[!code-csharpMain]

   1:  studentRepository.UpdateStudent(student);
   2:  studentRepository.Save();

[!code-csharpMain]

   1:  studentRepository.DeleteStudent(id);
   2:  studentRepository.Save();

And the Dispose method now disposes the repository instead of the context:

[!code-csharpMain]

   1:  studentRepository.Dispose();

Run the site and click the Students tab.

Students_Index_page
Students_Index_page

The page looks and works the same as it did before you changed the code to use the repository, and the other Student pages also work the same. However, there’s an important difference in the way the Index method of the controller does filtering and ordering. The original version of this method contained the following code:

[!code-csharpMain]

   1:  var students = from s in context.Students
   2:                 select s;
   3:  if (!String.IsNullOrEmpty(searchString))
   4:  {
   5:      students = students.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper())
   6:                             || s.FirstMidName.ToUpper().Contains(searchString.ToUpper()));
   7:  }

The updated Index method contains the following code:

[!code-csharpMain]

   1:  var students = from s in studentRepository.GetStudents()
   2:                  select s;
   3:  if (!String.IsNullOrEmpty(searchString))
   4:  {
   5:      students = students.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper())
   6:                          || s.FirstMidName.ToUpper().Contains(searchString.ToUpper()));
   7:  }

Only the highlighted code has changed.

In the original version of the code, students is typed as an IQueryable object. The query isn’t sent to the database until it’s converted into a collection using a method such as ToList, which doesn’t occur until the Index view accesses the student model. The Where method in the original code above becomes a WHERE clause in the SQL query that is sent to the database. That in turn means that only the selected entities are returned by the database. However, as a result of changing context.Students to studentRepository.GetStudents(), the students variable after this statement is an IEnumerable collection that includes all students in the database. The end result of applying the Where method is the same, but now the work is done in memory on the web server and not by the database. For queries that return large volumes of data, this can be inefficient.

[!TIP]

IQueryable vs. IEnumerable

After you implement the repository as shown here, even if you enter something in the Search box the query sent to SQL Server returns all Student rows because it doesn’t include your search criteria:

[!code-sqlMain]

   1:  SELECT 
   2:  '0X0X' AS [C1], 
   3:  [Extent1].[PersonID] AS [PersonID], 
   4:  [Extent1].[LastName] AS [LastName], 
   5:  [Extent1].[FirstName] AS [FirstName], 
   6:  [Extent1].[EnrollmentDate] AS [EnrollmentDate]
   7:  FROM [dbo].[Person] AS [Extent1]
   8:  WHERE [Extent1].[Discriminator] = N'Student'

This query returns all of the student data because the repository executed the query without knowing about the search criteria. The process of sorting, applying search criteria, and selecting a subset of the data for paging (showing only 3 rows in this case) is done in memory later when the ToPagedList method is called on the IEnumerable collection.

In the previous version of the code (before you implemented the repository), the query is not sent to the database until after you apply the search criteria, when ToPagedList is called on the IQueryable object.

When ToPagedList is called on an IQueryable object, the query sent to SQL Server specifies the search string, and as a result only rows that meet the search criteria are returned, and no filtering needs to be done in memory.

[!code-sqlMain]

   1:  exec sp_executesql N'SELECT TOP (3) 
   2:  [Project1].[StudentID] AS [StudentID], 
   3:  [Project1].[LastName] AS [LastName], 
   4:  [Project1].[FirstName] AS [FirstName], 
   5:  [Project1].[EnrollmentDate] AS [EnrollmentDate]
   6:  FROM ( SELECT [Project1].[StudentID] AS [StudentID], [Project1].[LastName] AS [LastName], [Project1].[FirstName] AS [FirstName], [Project1].[EnrollmentDate] AS [EnrollmentDate], row_number() OVER (ORDER BY [Project1].[LastName] ASC) AS [row_number]
   7:  FROM ( SELECT 
   8:      [Extent1].[StudentID] AS [StudentID], 
   9:      [Extent1].[LastName] AS [LastName], 
  10:      [Extent1].[FirstName] AS [FirstName], 
  11:      [Extent1].[EnrollmentDate] AS [EnrollmentDate]
  12:      FROM [dbo].[Student] AS [Extent1]
  13:      WHERE (( CAST(CHARINDEX(UPPER(@p__linq__0), UPPER([Extent1].[LastName])) AS int)) > 0) OR (( CAST(CHARINDEX(UPPER(@p__linq__1), UPPER([Extent1].[FirstName])) AS int)) > 0)
  14:  )  AS [Project1]
  15:  )  AS [Project1]
  16:  WHERE [Project1].[row_number] > 0
  17:  ORDER BY [Project1].[LastName] ASC',N'@p__linq__0 nvarchar(4000),@p__linq__1 nvarchar(4000)',@p__linq__0=N'Alex',@p__linq__1=N'Alex'

(The following tutorial explains how to examine queries sent to SQL Server.)

The following section shows how to implement repository methods that enable you to specify that this work should be done by the database.

You’ve now created an abstraction layer between the controller and the Entity Framework database context. If you were going to perform automated unit testing with this application, you could create an alternative repository class in a unit test project that implements IStudentRepository. Instead of calling the context to read and write data, this mock repository class could manipulate in-memory collections in order to test controller functions.

Implement a Generic Repository and a Unit of Work Class

Creating a repository class for each entity type could result in a lot of redundant code, and it could result in partial updates. For example, suppose you have to update two different entity types as part of the same transaction. If each uses a separate database context instance, one might succeed and the other might fail. One way to minimize redundant code is to use a generic repository, and one way to ensure that all repositories use the same database context (and thus coordinate all updates) is to use a unit of work class.

In this section of the tutorial, you’ll create a GenericRepository class and a UnitOfWork class, and use them in the Course controller to access both the Department and the Course entity sets. As explained earlier, to keep this part of the tutorial simple, you aren’t creating interfaces for these classes. But if you were going to use them to facilitate TDD, you’d typically implement them with interfaces the same way you did the Student repository.

Create a Generic Repository

In the DAL folder, create GenericRepository.cs and replace the existing code with the following code:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Data;
   5:  using System.Data.Entity;
   6:  using ContosoUniversity.Models;
   7:  using System.Linq.Expressions;
   8:   
   9:  namespace ContosoUniversity.DAL
  10:  {
  11:      public class GenericRepository<TEntity> where TEntity : class
  12:      {
  13:          internal SchoolContext context;
  14:          internal DbSet<TEntity> dbSet;
  15:   
  16:          public GenericRepository(SchoolContext context)
  17:          {
  18:              this.context = context;
  19:              this.dbSet = context.Set<TEntity>();
  20:          }
  21:   
  22:          public virtual IEnumerable<TEntity> Get(
  23:              Expression<Func<TEntity, bool>> filter = null,
  24:              Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
  25:              string includeProperties = "")
  26:          {
  27:              IQueryable<TEntity> query = dbSet;
  28:   
  29:              if (filter != null)
  30:              {
  31:                  query = query.Where(filter);
  32:              }
  33:   
  34:              foreach (var includeProperty in includeProperties.Split
  35:                  (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
  36:              {
  37:                  query = query.Include(includeProperty);
  38:              }
  39:   
  40:              if (orderBy != null)
  41:              {
  42:                  return orderBy(query).ToList();
  43:              }
  44:              else
  45:              {
  46:                  return query.ToList();
  47:              }
  48:          }
  49:   
  50:          public virtual TEntity GetByID(object id)
  51:          {
  52:              return dbSet.Find(id);
  53:          }
  54:   
  55:          public virtual void Insert(TEntity entity)
  56:          {
  57:              dbSet.Add(entity);
  58:          }
  59:   
  60:          public virtual void Delete(object id)
  61:          {
  62:              TEntity entityToDelete = dbSet.Find(id);
  63:              Delete(entityToDelete);
  64:          }
  65:   
  66:          public virtual void Delete(TEntity entityToDelete)
  67:          {
  68:              if (context.Entry(entityToDelete).State == EntityState.Detached)
  69:              {
  70:                  dbSet.Attach(entityToDelete);
  71:              }
  72:              dbSet.Remove(entityToDelete);
  73:          }
  74:   
  75:          public virtual void Update(TEntity entityToUpdate)
  76:          {
  77:              dbSet.Attach(entityToUpdate);
  78:              context.Entry(entityToUpdate).State = EntityState.Modified;
  79:          }
  80:      }
  81:  }

Class variables are declared for the database context and for the entity set that the repository is instantiated for:

[!code-csharpMain]

   1:  internal SchoolContext context;
   2:  internal DbSet dbSet;

The constructor accepts a database context instance and initializes the entity set variable:

[!code-csharpMain]

   1:  public GenericRepository(SchoolContext context)
   2:  {
   3:      this.context = context;
   4:      this.dbSet = context.Set<TEntity>();
   5:  }

The Get method uses lambda expressions to allow the calling code to specify a filter condition and a column to order the results by, and a string parameter lets the caller provide a comma-delimited list of navigation properties for eager loading:

[!code-csharpMain]

   1:  public virtual IEnumerable<TEntity> Get(
   2:      Expression<Func<TEntity, bool>> filter = null,
   3:      Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
   4:      string includeProperties = "")

The code Expression<Func<TEntity, bool>> filter means the caller will provide a lambda expression based on the TEntity type, and this expression will return a Boolean value. For example, if the repository is instantiated for the Student entity type, the code in the calling method might specify student => student.LastName == "Smith" for the filter parameter.

The code Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy also means the caller will provide a lambda expression. But in this case, the input to the expression is an IQueryable object for the TEntity type. The expression will return an ordered version of that IQueryable object. For example, if the repository is instantiated for the Student entity type, the code in the calling method might specify q => q.OrderBy(s => s.LastName) for the orderBy parameter.

The code in the Get method creates an IQueryable object and then applies the filter expression if there is one:

[!code-csharpMain]

   1:  IQueryable<TEntity> query = dbSet;
   2:   
   3:  if (filter != null)
   4:  {
   5:      query = query.Where(filter);
   6:  }

Next it applies the eager-loading expressions after parsing the comma-delimited list:

[!code-csharpMain]

   1:  foreach (var includeProperty in includeProperties.Split
   2:      (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) 
   3:  { 
   4:      query = query.Include(includeProperty); 
   5:  }

Finally, it applies the orderBy expression if there is one and returns the results; otherwise it returns the results from the unordered query:

[!code-csharpMain]

   1:  if (orderBy != null)
   2:  {
   3:      return orderBy(query).ToList();
   4:  }
   5:  else
   6:  {
   7:      return query.ToList();
   8:  }

When you call the Get method, you could do filtering and sorting on the IEnumerable collection returned by the method instead of providing parameters for these functions. But the sorting and filtering work would then be done in memory on the web server. By using these parameters, you ensure that the work is done by the database rather than the web server. An alternative is to create derived classes for specific entity types and add specialized Get methods, such as GetStudentsInNameOrder or GetStudentsByName. However, in a complex application, this can result in a large number of such derived classes and specialized methods, which could be more work to maintain.

The code in the GetByID, Insert, and Update methods is similar to what you saw in the non-generic repository. (You aren’t providing an eager loading parameter in the GetByID signature, because you can’t do eager loading with the Find method.)

Two overloads are provided for the Delete method:

[!code-csharpMain]

   1:  public virtual void Delete(object id)
   2:  {
   3:      TEntity entityToDelete = dbSet.Find(id);
   4:      dbSet.Remove(entityToDelete);
   5:  }
   6:   
   7:  public virtual void Delete(TEntity entityToDelete)
   8:  {
   9:      if (context.Entry(entityToDelete).State == EntityState.Detached)
  10:      {
  11:          dbSet.Attach(entityToDelete);
  12:      }
  13:      dbSet.Remove(entityToDelete);
  14:  }

One of these lets you pass in just the ID of the entity to be deleted, and one takes an entity instance. As you saw in the Handling Concurrency tutorial, for concurrency handling you need a Delete method that takes an entity instance that includes the original value of a tracking property.

This generic repository will handle typical CRUD requirements. When a particular entity type has special requirements, such as more complex filtering or ordering, you can create a derived class that has additional methods for that type.

Creating the Unit of Work Class

The unit of work class serves one purpose: to make sure that when you use multiple repositories, they share a single database context. That way, when a unit of work is complete you can call the SaveChanges method on that instance of the context and be assured that all related changes will be coordinated. All that the class needs is a Save method and a property for each repository. Each repository property returns a repository instance that has been instantiated using the same database context instance as the other repository instances.

In the DAL folder, create a class file named UnitOfWork.cs and replace the template code with the following code:

[!code-csharpMain]

   1:  using System;
   2:  using ContosoUniversity.Models;
   3:   
   4:  namespace ContosoUniversity.DAL
   5:  {
   6:      public class UnitOfWork : IDisposable
   7:      {
   8:          private SchoolContext context = new SchoolContext();
   9:          private GenericRepository<Department> departmentRepository;
  10:          private GenericRepository<Course> courseRepository;
  11:   
  12:          public GenericRepository<Department> DepartmentRepository
  13:          {
  14:              get
  15:              {
  16:                  return this.departmentRepository ?? new GenericRepository<Department>(context);
  17:              }
  18:          }
  19:   
  20:          public GenericRepository<Course> CourseRepository
  21:          {
  22:              get
  23:              {
  24:                  return this.courseRepository ?? new GenericRepository<Course>(context);
  25:              }
  26:          }
  27:   
  28:          public void Save()
  29:          {
  30:              context.SaveChanges();
  31:          }
  32:   
  33:          private bool disposed = false;
  34:   
  35:          protected virtual void Dispose(bool disposing)
  36:          {
  37:              if (!this.disposed)
  38:              {
  39:                  if (disposing)
  40:                  {
  41:                      context.Dispose();
  42:                  }
  43:              }
  44:              this.disposed = true;
  45:          }
  46:   
  47:          public void Dispose()
  48:          {
  49:              Dispose(true);
  50:              GC.SuppressFinalize(this);
  51:          }
  52:      }
  53:  }

The code creates class variables for the database context and each repository. For the context variable, a new context is instantiated:

[!code-csharpMain]

   1:  private SchoolContext context = new SchoolContext();
   2:  private GenericRepository<Department> departmentRepository;
   3:  private GenericRepository<Course> courseRepository;

Each repository property checks whether the repository already exists. If not, it instantiates the repository, passing in the context instance. As a result, all repositories share the same context instance.

[!code-csharpMain]

   1:  public GenericRepository<Department> DepartmentRepository
   2:  {
   3:      get
   4:      {
   5:   
   6:          if (this.departmentRepository == null)
   7:          {
   8:              this.departmentRepository = new GenericRepository<Department>(context);
   9:          }
  10:          return departmentRepository;
  11:      }
  12:  }

The Save method calls SaveChanges on the database context.

Like any class that instantiates a database context in a class variable, the UnitOfWork class implements IDisposable and disposes the context.

Changing the Course Controller to use the UnitOfWork Class and Repositories

Replace the code you currently have in CourseController.cs with the following code:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Data;
   4:  using System.Data.Entity;
   5:  using System.Linq;
   6:  using System.Web;
   7:  using System.Web.Mvc;
   8:  using ContosoUniversity.Models;
   9:  using ContosoUniversity.DAL;
  10:   
  11:  namespace ContosoUniversity.Controllers
  12:  {
  13:     public class CourseController : Controller
  14:     {
  15:        private UnitOfWork unitOfWork = new UnitOfWork();
  16:   
  17:        //
  18:        // GET: /Course/
  19:   
  20:        public ViewResult Index()
  21:        {
  22:           var courses = unitOfWork.CourseRepository.Get(includeProperties: "Department");
  23:           return View(courses.ToList());
  24:        }
  25:   
  26:        //
  27:        // GET: /Course/Details/5
  28:   
  29:        public ViewResult Details(int id)
  30:        {
  31:           Course course = unitOfWork.CourseRepository.GetByID(id);
  32:           return View(course);
  33:        }
  34:   
  35:        //
  36:        // GET: /Course/Create
  37:   
  38:        public ActionResult Create()
  39:        {
  40:           PopulateDepartmentsDropDownList();
  41:           return View();
  42:        }
  43:   
  44:        [HttpPost]
  45:        [ValidateAntiForgeryToken]
  46:        public ActionResult Create(
  47:            [Bind(Include = "CourseID,Title,Credits,DepartmentID")]
  48:           Course course)
  49:        {
  50:           try
  51:           {
  52:              if (ModelState.IsValid)
  53:              {
  54:                 unitOfWork.CourseRepository.Insert(course);
  55:                 unitOfWork.Save();
  56:                 return RedirectToAction("Index");
  57:              }
  58:           }
  59:           catch (DataException /* dex */)
  60:           {
  61:              //Log the error (uncomment dex variable name after DataException and add a line here to write a log.)
  62:              ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
  63:           }
  64:           PopulateDepartmentsDropDownList(course.DepartmentID);
  65:           return View(course);
  66:        }
  67:   
  68:        public ActionResult Edit(int id)
  69:        {
  70:           Course course = unitOfWork.CourseRepository.GetByID(id);
  71:           PopulateDepartmentsDropDownList(course.DepartmentID);
  72:           return View(course);
  73:        }
  74:   
  75:        [HttpPost]
  76:        [ValidateAntiForgeryToken]
  77:        public ActionResult Edit(
  78:             [Bind(Include = "CourseID,Title,Credits,DepartmentID")]
  79:           Course course)
  80:        {
  81:           try
  82:           {
  83:              if (ModelState.IsValid)
  84:              {
  85:                 unitOfWork.CourseRepository.Update(course);
  86:                 unitOfWork.Save();
  87:                 return RedirectToAction("Index");
  88:              }
  89:           }
  90:           catch (DataException /* dex */)
  91:           {
  92:              //Log the error (uncomment dex variable name after DataException and add a line here to write a log.)
  93:              ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
  94:           }
  95:           PopulateDepartmentsDropDownList(course.DepartmentID);
  96:           return View(course);
  97:        }
  98:   
  99:        private void PopulateDepartmentsDropDownList(object selectedDepartment = null)
 100:        {
 101:           var departmentsQuery = unitOfWork.DepartmentRepository.Get(
 102:               orderBy: q => q.OrderBy(d => d.Name));
 103:           ViewBag.DepartmentID = new SelectList(departmentsQuery, "DepartmentID", "Name", selectedDepartment);
 104:        }
 105:   
 106:        //
 107:        // GET: /Course/Delete/5
 108:   
 109:        public ActionResult Delete(int id)
 110:        {
 111:           Course course = unitOfWork.CourseRepository.GetByID(id);
 112:           return View(course);
 113:        }
 114:   
 115:        //
 116:        // POST: /Course/Delete/5
 117:   
 118:        [HttpPost, ActionName("Delete")]
 119:        [ValidateAntiForgeryToken]
 120:        public ActionResult DeleteConfirmed(int id)
 121:        {
 122:           Course course = unitOfWork.CourseRepository.GetByID(id);
 123:           unitOfWork.CourseRepository.Delete(id);
 124:           unitOfWork.Save();
 125:           return RedirectToAction("Index");
 126:        }
 127:   
 128:        protected override void Dispose(bool disposing)
 129:        {
 130:           unitOfWork.Dispose();
 131:           base.Dispose(disposing);
 132:        }
 133:     }
 134:  }

This code adds a class variable for the UnitOfWork class. (If you were using interfaces here, you wouldn’t initialize the variable here; instead, you’d implement a pattern of two constructors just as you did for the Student repository.)

[!code-csharpMain]

   1:  private UnitOfWork unitOfWork = new UnitOfWork();

In the rest of the class, all references to the database context are replaced by references to the appropriate repository, using UnitOfWork properties to access the repository. The Dispose method disposes the UnitOfWork instance.

[!code-csharpMain]

   1:  var courses = unitOfWork.CourseRepository.Get(includeProperties: "Department");
   2:  // ...
   3:  Course course = unitOfWork.CourseRepository.GetByID(id);
   4:  // ...
   5:  unitOfWork.CourseRepository.Insert(course);
   6:  unitOfWork.Save();
   7:  // ...
   8:  Course course = unitOfWork.CourseRepository.GetByID(id);
   9:  // ...
  10:  unitOfWork.CourseRepository.Update(course);
  11:  unitOfWork.Save();
  12:  // ...
  13:  var departmentsQuery = unitOfWork.DepartmentRepository.Get(
  14:      orderBy: q => q.OrderBy(d => d.Name));
  15:  // ...
  16:  Course course = unitOfWork.CourseRepository.GetByID(id);
  17:  // ...
  18:  unitOfWork.CourseRepository.Delete(id);
  19:  unitOfWork.Save();
  20:  // ...
  21:  unitOfWork.Dispose();

Run the site and click the Courses tab.

Courses_Index_page
Courses_Index_page

The page looks and works the same as it did before your changes, and the other Course pages also work the same.

Summary

You have now implemented both the repository and unit of work patterns. You have used lambda expressions as method parameters in the generic repository. For more information about how to use these expressions with an IQueryable object, see IQueryable(T) Interface (System.Linq) in the MSDN Library. In the next tutorial you’ll learn how to handle some advanced scenarios.

Links to other Entity Framework resources can be found in the ASP.NET Data Access Content Map.

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application.htm
< THANKS ME>