Guest User

Service & Repository for Master Management

a guest
May 30th, 2017
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. ///////////////////////  Model classes /////////////////////////////////////////////////////////////
  2. public class _ModelBaseMaster
  3. {
  4.     public int id{get;set;}
  5.     public string name{get;set;}
  6. }
  7. public class Master1: _ModelBaseMaster{}
  8.  
  9. ////////////////////////// Generic repository for DAL /////////////////////////////////////////////
  10. public class RepositoryMaster<T> where T : _ModelBaseMaster
  11.     {
  12.         // This is the generic repository for master tables which will handle CRUD & fetch
  13.         public RepositoryMaster(MyDBContext context){...}
  14.         ...
  15.     }
  16.  
  17. ///////////////////////// Service Interface and its implementation /////////////////////////////////
  18. public interface IMasterService<T> : IBaseService where T: _IModelBaseMaster
  19. {
  20.     List<T> FetchAll();
  21.     void Add(T mObj);
  22.     ...
  23. }
  24.  
  25. public class MasterService<T> : _ServiceBase, IMasterService<T> where T : _ModelBaseMaster
  26. {
  27.     IRepositoryMaster<T> mstrRepo;
  28.     public MasterService(IRepositoryMaster<T> mRepository)
  29.         {
  30.             mstrRepo = mRepository;
  31.         }
  32.     public List<T> FetchAll()
  33.     {
  34.         IQueryable<T> data = mstrRepo.FetchAll();
  35.         // I can do - List<_ModelBaseMaster> result = data.Cast<_ModelBaseMaster>().ToList();
  36.         ...
  37.         return data.Cast<T>().ToList();
  38.     }
  39.     public void Add(T mObj)
  40.     {
  41.         mstrRepo.Insert(mObj); // can it be this simple - and work for ALL master tables ?
  42.     }
  43.    
  44. }
  45.  
  46. /////////////////////////// usage in MVC controller's action /////////////////////////////////////
  47.  
  48. // Now I want to be able to initialize as -
  49.  
  50. MasterService<_ModelBaseMaster> mstrService = new RepositoryMaster<Master1>(context);
  51.  
  52. // And finally -
  53.  
  54. List<_ModelBaseMaster> genericList = mstrService.FetchAll();
  55.  
  56. //- this will prevent me from lengthy switch case for each master table
Add Comment
Please, Sign In to add comment