The repository pattern in MVC

Source: Internet
Author: User

1. First create an empty MVC3 application named Myrepository.web, and the solution is named Myrepository.

2. Add a class library project named Myrepository.dal and add a folder named Repository to hold the business logic.

3. Continue to add a class library project named Myrepository.domain, add two folders models and infrastructure.

Models to store entities, infrastructure to store several basic classes. The directory structure is now ready.

4. Use NuGet to ensure that three projects have the same version of EF added, referencing myrepository.domain in Myrepository.dal,

Myrepository.domain and Myrepository.dal are referenced in Myrepository.web.

5. Add a class Bookstoredbcontext in the Myrepository.domain. Use EF to connect to a database.

 Public class Bookstoredbcontext:dbcontext
{
// EF looks for name=bookstore database links from the configuration file.
// If you do not specify: base ("Bookstore"), look for the Name=bookstoredbcontext database connection
Public Bookstoredbcontext ()
Base ("bookstore")
{

}
}

Here is the configuration file:

  <connectionStrings>
<add name="bookstore" providername="System.Data.SqlClient" connectionstring="Data source=.\sqlexpress;initial Catalog=bookstore; User id=wangzx; password=wangzx01; Persist Security info=true; "/>
</connectionStrings>

DbContext is used to establish a connection with the database to complete the operation of the data, if the repository mode is not used, the instantiation of the DbContext is generally placed in the controller to use. The following is the beginning of the introduction to MVC3 using repository mode.

First, the class diagram of the repository pattern is affixed:

6. First introduce the most important interface irepository, which defines the most common business logic operations: Add, delete, and so on. These actions are the same for any one entity. This class is added to the infrastructure folder of the Myrepository.domain project.

Here's the code:

namespace MyRepository.Domain.Infrastructure
{
Public Interface where class
{
void Insert (TEntity entity);
void Update (TEntity entity);
void Delete (TEntity entity);
}
}

The generic interface is used here, which can be used for the operation of different entities such as Book,author, as long as the stand-up character is replaced.

7. The following is the repository generic base class, which implements the IRepository interface and uses a generic implementation for operations on multiple different entities.

The specific operation is implemented by DbContext, so a dbcontext parameter is provided in the constructor. The class is located under the same directory as the irepository.

Code:

namespaceMyRepository.Domain.Infrastructure
{
Public classRepository<tentity>: irepository<tentity>whereTEntity:class
{
protectedBookstoredbcontext DbContext;
protectedDbset<tentity> DbSet;

PublicRepository (Bookstoredbcontext dbContext)
{
This. DbContext = DbContext;
This. DbSet = Dbcontext.set<tentity> ();
}
Public voidInsert (TEntity entity)
{
Dbset.add (entity);
}
Public voidUpdate (TEntity entity)
{
Dbset.attach (entity);
Dbcontext.entry (entity). state = entitystate.modified;
}
Public voidDelete (TEntity entity)
{
if(Dbcontext.entry (entity). state = = entitystate.detached)
{
Dbset.attach (entity);
}
Dbset.remove (entity);
}
}
}

The Repository class is the generic implementation of general business operations, mainly the modification of the database query operation. The following unitofwork and Iunitofwork also belong to infrastructure, both of which are used to save data. Both repository and unitofwork use DbContext to manipulate the database, so there is a dbcontext field.

 Public Interface Iunitofwork:idisposable
{
get; }
void Save ();
BOOL get; }
}
 /// <summary>
///for saving operations on data
/// </summary>
Public classUnitofwork:iunitofwork
{
Private ReadOnlyBookstoredbcontext _context;
PublicDbContext Context
{
Get{return_context; }
}

Public EventEventHandler disposed;

Public BOOLisdisposed {Get;Private Set; }
Public voidDispose ()
{
Dispose (true);
}
Public Virtual voidDispose (BOOLDisposing
{
Lock( This)
{
if(Disposing &&!) isdisposed)
{
_context. Dispose ();
varEVT = disposed;
if(EVT! =NULL) evt ( This, Eventargs.empty);
disposed =NULL;
isdisposed =true;
Gc. SuppressFinalize ( This);
}
}
}

PublicUnitofwork (Bookstoredbcontext context)
{
_context = context;
}

Public voidSave ()
{
_context. SaveChanges ();
}

~unitofwork ()
{
Dispose (false);
}
}

By now the framework of the repository model has been set up, using the book entity to complete a specific business operation, the following steps for the operation of other entities.

8.1: Add entity

Add an entity class book below the MyRepository.Domain.Models folder.

[Table (" Book")]
Public classBook
{
Public intId {Get;Set; }

Public stringISBN {Get;Set; }

Public stringTitle {Get;Set; }

Public stringType {Get;Set; }
}

8.2: Modify DbContext

Then modify our DbContext class to add a Dbset attribute so that EF adds a book table to the database.

  Public classBookstoredbcontext:dbcontext
{
//EF looks for name=bookstore database links from the configuration file.
//If you do not specify: base ("Bookstore"), look for the Name=bookstoredbcontext database connection
PublicBookstoredbcontext ()
:Base("Bookstore")
{

}

PublicDbset<book> Bookcollection {Get;Set; }
}

8.3: Add Ixxxrepository interface

In the Repository class diagram, only the irepoitory and repository two common classes are described, while Ixxxrepository and xxxrepository are classes that are added when used specifically. Below, add a ibookrepository below the Myrepository.domain folder, which is an extension of the existing book entity business. You can see that the interface contains more operations than the IRepository interface.

     Public Interface Ibookrepository:irepository<book>
{
// Other business operations, the interface is generally used in the controller
Ilist<book> Getallbooks ();
}

8.4: Implement Bookrepository

Add a Bookrepository class below the MyRepository.DAL.Repository directory.

  Public classBookrepository:repository<book>, ibookrepository
{
//execute the constructor of the base class repository<book> before executing the subclass constructor
PublicBookrepository (Bookstoredbcontext DbContext)
:Base(DbContext)
{
}

PublicIlist<book> Getallbookbytype (stringType
{
varList = DbContext.BookCollection.Where (x = = X.type = = Type);
returnList. (x = X.ISBN). ToList ();
}
}

The Bookrepository class inherits all the business operations on the book entity, and the public operation is in Repository<book>. Because Bookrepository inherits from Repository<book>, and Repository<tentity> inherits and implements Irepository<tentity> So bookrepository does not need to implement the method of Irepository<tentity> interface definition again, if need can overwrite repository<book> public operation.

The unique business operations of bookrepository are defined in ibookrepository and must be implemented in Bookrepository. Ibookrepository must inherit from IRepository so that ibookrepository in the controller can contain all the actions of bookrepository. Ibookrepository can reference bookrepository objects well when the controller is combined with IOC.

In fact, in enterprise projects, the C and V operations in Bookrepository and Myrepository.web are not synchronized. That is, not immediately after the completion of the bookrepository to write Bookcontroller, in a controller may contain multiple Ixxxrepository interface types of properties, when constructed to receive xxxrepository objects. But here I write a simple bookcontroller and do not use IOC to briefly introduce repository mode.

9

Add a controller to the MyRepository.Web.Controllers MyRepository.Web.BookController

 Public classBookcontroller:controller
{
PrivateIbookrepository bookrepository;
PrivateIunitofwork unitofwork;

PublicBookcontroller ()
{
Bookstoredbcontext Bookstoredbcontext =NewBookstoredbcontext ();
Bookrepository =NewBookrepository (Bookstoredbcontext);
Unitofwork =NewUnitofwork (Bookstoredbcontext);
}

PublicViewResult List ()
{
ilist<book> Listbook = Bookrepository.getallbooks ();
returnView (Listbook);
}

[HttpGet]
PublicViewResult Create ()
{
returnView ();
}

[HttpPost]
PublicActionResult Create (book book)
{
Bookrepository.insert (book);
Unitofwork.save ();
returnRedirecttoaction ("List");
}
}

For the addition of view, the routing setting belongs to the content of MVC3: http://www.bbsmvc.com/mvclearn/thread-173-1-1.html. Also mentioned in MVC3 's book is the IOC's ability to combine this. Here is the database and run effect.

 


The repository pattern in MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.