Repository mode, repository
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 advantage of using this mode is to decouple the domain model from the customer code and 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:
interface IRepository<T> where T : class{ IEnumerable<T> FindAll(Func<T, bool> exp); void Add(T entity); void Delete(T entity); void Save();}
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:
interface IBookRepository : IRepository<Book>{ IList<Book> GetAllByBookId(int id);}
4. The Repository class of the object is implemented as follows:
public class BookRepository : Repository<Book>, IBookRepository{ public BookRepository(DataContext dc) : base(dc) { } public IList<Book> GetAllByBookId(int id) { var listbook = from c in context.GetTable<Book>() where c.BookId == id select c; return listbook.ToList(); }}
The above is just a basic framework for everyone.
This article is from: http://www.cnblogs.com/carysun/archive/2009/03/20/repository.html# for learning only