Brian David Berman: Technical Blog

May 7, 2009

Super Simple Repository Pattern Example

Filed under: ASP.NET, ASP.NET MVC — briandberman @ 8:52 pm

After reading Chapter 1 of Professional ASP.NET MVC 1.0, I got a nice introduction to the “repository” pattern.  Using a repository helps us separate concerns, which is a big part of (but not limited to) ASP.NET MVC.  Let’s start off really simple by looking at a table (called Employees) I created and dragged into the LINQ to SQL Designer in Visual Studio 2008:

image

Once we save our .dbml file, Visual Studio 2008 creates an “Employee” class that exposes the available properties, allowing us to persist data back to our database.  A simple way to add a new record to this table is as follows:

   1: CompanyDataContext companyDataContext = new CompanyDataContext();
   2:  
   3: Employee employee = new Employee();
   4:  
   5: employee.LastName = "Berman";
   6: employee.FirstName = "Brian";
   7: employee.JobTitle = "Software Engineer";
   8: employee.Extension = "1234";
   9: employee.HireDate = DateTime.Parse("01/01/2006");
  10:  
  11: companyDataContext.Employees.InsertOnSubmit(employee);
  12: companyDataContext.SubmitChanges();

The above produces the following result in the database:

image

While this may be a fine way to update a table, it is difficult to test and requires mention of the data context, as well as data storage implementation (LINQ to SQL) methods.  To fix this, we can add a “repository” layer:

   1: public class EmployeeRepository
   2: {
   3:     CompanyDataContext companyDataContext = new CompanyDataContext();
   4:  
   5:     public void Add(Employee employee)
   6:     {
   7:         companyDataContext.Employees.InsertOnSubmit(employee);
   8:     }
   9:  
  10:     public void Save()
  11:     {
  12:         companyDataContext.SubmitChanges();
  13:     }
  14: }

The repository class contains the data storage implementation activity, including the data context and methods.  We can then change our original code to the following:

   1: EmployeeRepository employeeRepository = new EmployeeRepository();
   2:  
   3: Employee employee = new Employee();
   4:  
   5: employee.LastName = "Yandle";
   6: employee.FirstName = "Justine";
   7: employee.JobTitle = "Teacher";
   8: employee.Extension = "5678";
   9: employee.HireDate = DateTime.Parse("01/01/2008");
  10:  
  11: employeeRepository.Add(employee);
  12: employeeRepository.Save();  

While this example doesn’t use less code, you will notice the “insert” and “save” functionality is handled through the database repository methods Add() and Save().  The result of running this code (along with our original code) produces the following in the database:

image

This allows our code to be more testable since we could now write unit tests against our objects without a database (mock objects).  Although less likely, we are also able to swap out our data storage implementation (e.g. going from LINQ to SQL to LINQ to Entities) at a later time in a much smoother fashion.  Some other example methods within the EmployeeRepository class are as follows:

   1: public class EmployeeRepository
   2:     {
   3:         CompanyDataContext companyDataContext = new CompanyDataContext();
   4:  
   5:         public IQueryable<Employee> FindAllEmployees()
   6:         {
   7:             return companyDataContext.Employees;
   8:         }
   9:  
  10:         public Dinner GetEmployee(int id)
  11:         {
  12:             return companyDataContext.Employees.SingleOrDefault(e => e.EmployeeId == id);
  13:         }
  14:  
  15:         public void Add(Employee employee)
  16:         {
  17:             companyDataContext.Employees.InsertOnSubmit(employee);
  18:         }
  19:  
  20:         public void Save()
  21:         {
  22:             companyDataContext.SubmitChanges();
  23:         }
  24:     }

Hopefully this explains the repository pattern in the simplest way possible.  Please feel free to leave comments.  I am still learning and wouldn’t mind learning more through comments!  ;-)

April 24, 2009

Fun with ASP.NET MVC leads to nice oO Design discovery (Updated)

Filed under: Uncategorized — briandberman @ 3:47 am

I was working through the first chapter of Professional ASP.NET MVC 1.0 and came across a really slick way to handle business rule violations.  Below is some sample code written by Scott Guthrie for the NerdDinner project.

   1: //
   2: // POST: /Dinners/Edit/2
   3: [AcceptVerbs(HttpVerbs.Post)]
   4: public ActionResult Edit(int id, FormCollection formValues)
   5: {
   6:     Dinner dinner = dinnerRepository.GetDinner(id);
   7:  
   8:     try
   9:     {
  10:         UpdateModel(dinner);
  11:  
  12:         dinnerRepository.Save();
  13:  
  14:         return RedirectToAction("Details", new { id = dinner.DinnerId });
  15:  
  16:     }
  17:  
  18:     catch
  19:     {
  20:         ModelState.AddRuleViolations(dinner.GetRuleViolations());
  21:  
  22:         return View(dinner);
  23:     }
  24: }

What’s going on here is that we are editing a Dinner object.  We pass in the ID of the Dinner we are editing as well as the form values from the form post.  At line 6, we instantiate a new dinner object based on the ID passed in.  We then “try” (lines 8-13) to update the model and save it back to the database.  If all goes well and the posted data is valid, the Dinner is saved and we are redirected (line 12).  If, on the other hand, something goes wrong (incorrect or incomplete data is passed in), it safe to say that a business rule has been violated.  Enter our “catch” (lines 14-19).  Since something went wrong, we update our model state with the violations from the GetRuleViolations method on the Dinner object.  We then return the dinner, showing the user the violations to fix.  I think this is, not only a great ASP.NET MVC example, but also a good OO design example.

(Update – Styles for code have been fixed. I am aware that I have some formatting issues.  I just opened this blog and haven’t looked at the CSS yet.  Thanks.)

April 23, 2009

My First Tech Blog Post

Filed under: Thoughts — briandberman @ 8:12 pm

After watching Scott Hanselman’s video on Social Networking for Developers, I’ve decided to take the plunge into technical blogging.  I’ll be posting thoughts, code samples, and anything I think is interesting and cool, when it comes to software development.  Thanks.

Blog at WordPress.com.