Advertisement
Guest User

Covariance based generic Master Managemnet Service

a guest
Jun 5th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 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<out 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 IEnumerable<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(object mObject)
  40.     {
  41.         var mObj = ConvertParentToChild<T>(mObject);
  42.         mstrRepo.Insert(mObj); // can it be this simple - and work for ALL master tables ?
  43.     }
  44.     ...
  45.     // The unconventional method to convert 'Parent' to 'Child'
  46.     // Use at your own risk (i.e. ensure that child do not have any extra properties)
  47.     // https://www.dotnetperls.com/generic-method
  48.         public static T ConvertParentToChild<T>(object parentInstance)
  49.         {
  50.             var serializedParent = JsonConvert.SerializeObject(parentInstance);
  51.             return JsonConvert.DeserializeObject<T>(serializedParent);
  52.         }
  53.    
  54. }
  55.  
  56. /////////////////////////// usage in MVC controller's action /////////////////////////////////////
  57.  
  58. // Now I can initialize as -
  59.  
  60. IMasterService<_ModelBaseMaster> mstrService = new RepositoryMaster<Master1>(context);
  61.  
  62. // And finally -
  63.  
  64. IEnumerable<_ModelBaseMaster> genericList = mstrService.FetchAll();
  65.  
  66. //- this will prevent me from lengthy switch case for each master table
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement