Recently, many examples of ASP. net mvc use the repository mode, such as oxite and scottgu recently released free ASP. net mvc tutorials. Let's take a look.
In enterprise architecture model, the translator translates repository into a resource library. The following description is provided:
Coordinates between the domain and the data ing layer by accessing an interface similar to a set of domain objects.
In "Domain-driven design: The Way to cope with software core complexity", the translator translates repository into a warehouse and provides the following description:
A mechanism used to encapsulate storage, read, and search behaviors. It simulates an object set.
The biggest benefit of using this model is to extract the domain model from the customerCodeIt is decoupled from the data ing layer.
Let's take a look at how to apply this mode in linqtosql.
1. we extract the public operation part of the object as the irepository interface, such as common addition and deletion methods. The following code:
InterfaceIrepository<T>WhereT:Class{Ienumerable<T> findall (Func<T,Bool> Exp );VoidAdd (T entity );VoidDelete (T entity );VoidSave ();}
2. Below we implement a generic class to implement the method of the above interface.
Public class Repository <T>: irepository <t> Where T: Class { Public Datacontext context; Public Repository (datacontext context ){ This . Context = context ;} Public Ienumerable <T> findall ( Func <T, Bool > Exp ){ Return Context. gettable <t> (). Where (exp );}Public void Add (T entity) {context. gettable <t> (). insertonsubmit (entity );} Public void Delete (T entity) {context. gettable <t> (). deleteonsubmit (entity );} Public void Save () {context. submitchanges ();}}
3. The above implementation is a public operation for each entity, but in reality each entity has its own business logic. We define another interface separately, for example:
InterfaceIbookrepository: Irepository <book> {Ilist<Book> getallbybookid (IntID );}
4. The repository class of the object is implemented as follows:
Public classBookrepository: Repository <book>, ibookrepository {PublicBookrepository (datacontext DC ):Base(Dc ){}PublicIlist<Book> getallbybookid (IntID ){VaRListbook =FromCInContext. gettable <book> ()WhereC. bookid = IDSelectC;ReturnListbook. tolist ();}}
The above is just a basic framework for everyone.