Repository Pattern

Repository Pattern:
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.

When to Use It

In a large system with many domain object types and many possible queries, Repository reduces the amount of code needed to deal with all the querying that goes on. Repository promotes the Specification pattern (in the form of the criteria object in the examples here), which encapsulates the query to be performed in a pure object-oriented way. Therefore, all the code for setting up a query object in specific cases can be removed. Clients need never think in SQL and can write code purely in terms of objects.


1.Define IRepository Interface;
public interface ICustomerRepository
    {        
        Customer GetCustomerById(string id);
        IEnumerable<Customer> FindByName(string name);
        void AddCustomer(Customer customer);
    }
2.Implement this Interface:
public class CustomerRepository : ICustomerRepository
    {
        private IDataContext _context;


        public CustomerRepository(IDataContext context)
        {
            _context = context;
        }


        public Customer GetCustomerById(string id)
        {
            return _context.Customers.GetCustomerById(id);
        }


        public void AddCustomer(Customer customer)
        {
            _context.Customers.AddCustomer(customer);
        }
    }


3.Define IDataContext
public interface IDataContext 
{
   Customer GetCustomerById(string id);
   IEnumerable<Customer> FindByName(string name);
}


4.SpecifiedDataContext : IDataContext
    {
        private IList<Customter> _customers;

         public SpecifiedDataContext()
        {
            _customers = new List<Customers>();
        }


        public IList<Customer> Customers
        {
            get 
            {
                return _customers;
            }
        }


        public Job Insert(Job job)
        {
            _jobs.Add(job);


            return job;
        }


        public bool CheckJob( Guid jobId )
        {
            return true;
        }


        public Job FindJob(Guid jobId)
        {
            var findJobs = from job in _jobs where job.Id == jobId select job;


            return findJobs.SingleOrDefault();
        }


        public void DeleteJob(Guid jobId)
        {
            DeleteJob(FindJob(jobId));
        }


        public void DeleteJob(Job job)
        {
            _jobs.Remove(job);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章