Repository pattern: One repository class for each entity?

前端 未结 4 1090
忘掉有多难
忘掉有多难 2020-12-05 00:50

Say you have the following entities defined in a LINQ class:

Product
Customer
Category

Should I have one repository class for all:

4条回答
  •  醉梦人生
    2020-12-05 01:23

    I'd have one repository/object because invariably, there'd need to be a map from my EntityTable to my domain object (such as in the body of the GetIQueryableCollection(). How I got around writing this repetitive code is by making a T4 template to generate it for me.

    I have an example project which generates the repository pattern on codeplex http://t4tarantino.codeplex.com/ T4 Toolbox example Templates for business classes and repository. It may not work exactly the way you'd like without some tweaking, unless you're already implementing Tarintino and a few other goodies, but the templates are easy to configure.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Cses.Core.Domain.Model;
    using StructureMap;
    
    namespace Cses.Core.Domain
    {
        /// 
        /// Core class for Schedule E
        /// 
        public class ScheduleERepository : IScheduleERepository
        {
    
            private Cses.Core.Repository.SqlDataContext _context = new Cses.Core.Repository.SqlDataContext();
    
            /// 
            /// constructor
            /// 
            public ScheduleERepository() { }
    
            /// 
            /// constructor for testing
            /// 
            /// 
            public ScheduleERepository(Cses.Core.Repository.SqlDataContext context)
            {
                _context = context;
    
            }
    
            /// 
            /// returns collection of scheduleE values
            /// 
            /// 
            public IQueryable GetIQueryableCollection()
            {           
                return from entity in _context.ScheduleEs                  
                   select new ScheduleE()
                   {    
                        Amount = entity.Amount,
                        NumberOfChildren = entity.NumberChildren,
                        EffectiveDate = entity.EffectiveDate,
                        MonthlyIncome = entity.MonthlyIncome,
                        ModifiedDate = entity.ModifiedDate,
                        ModifiedBy = entity.ModifiedBy,                      
                        Id = entity.Id                          
                   };           
            }
    

提交回复
热议问题