Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 9: Creating Web Applications with ASP.NET MVC 265
Creating a Repository
A common pattern for working with data is to build a repository that is responsible for all
data-related operations. This is another way to promote separation of concerns so that you
isolate logic into specific parts of an application, resulting in easier code to work with.
A repository is a class that performs create, read, update, and delete (CRUD) operations
on a specific data type. Listing 9-6 shows a repository for working with customer objects.
You can create this class by right-clicking the Models folder and selecting Add | Class,
and name the class CustomerRepository. The code also assumes that you’ve created a
LINQ to SQL *.dbml, named MyShop, with a Customer entity for the Customers table in
MyShop, which is the database created in Chapter 7.
Listing 9-6 A repository for working with customer data
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyShopCS.Models
{
public class CustomerRepository
{
private MyShopDataContext m_ctx
= new MyShopDataContext();
public int InsertCustomer(Customer cust)
{
m_ctx.Customers.InsertOnSubmit(cust);
m_ctx.SubmitChanges();
return cust.CustomerID;
}
public void UpdateCustomer(Customer cust)
{
var currentCust =
(from currCust in m_ctx.Customers
where currCust.CustomerID == cust.CustomerID
select currCust)
.SingleOrDefault();
if (currentCust != null)