Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /////////////////////// Model classes /////////////////////////////////////////////////////////////
- public class _ModelBaseMaster
- {
- public int id{get;set;}
- public string name{get;set;}
- }
- public class Master1: _ModelBaseMaster{}
- ////////////////////////// Generic repository for DAL /////////////////////////////////////////////
- public class RepositoryMaster<T> where T : _ModelBaseMaster
- {
- // This is the generic repository for master tables which will handle CRUD & fetch
- public RepositoryMaster(MyDBContext context){...}
- ...
- }
- ///////////////////////// Service Interface and its implementation /////////////////////////////////
- public interface IMasterService<out T> : IBaseService where T: _IModelBaseMaster
- {
- List<T> FetchAll();
- void Add(T mObj);
- ...
- }
- public class MasterService<T> : _ServiceBase, IMasterService<T> where T : _ModelBaseMaster
- {
- IRepositoryMaster<T> mstrRepo;
- public MasterService(IRepositoryMaster<T> mRepository)
- {
- mstrRepo = mRepository;
- }
- public IEnumerable<T> FetchAll()
- {
- IQueryable<T> data = mstrRepo.FetchAll();
- // I can do - List<_ModelBaseMaster> result = data.Cast<_ModelBaseMaster>().ToList();
- ...
- return data.Cast<T>().ToList();
- }
- public void Add(object mObject)
- {
- var mObj = ConvertParentToChild<T>(mObject);
- mstrRepo.Insert(mObj); // can it be this simple - and work for ALL master tables ?
- }
- ...
- // The unconventional method to convert 'Parent' to 'Child'
- // Use at your own risk (i.e. ensure that child do not have any extra properties)
- // https://www.dotnetperls.com/generic-method
- public static T ConvertParentToChild<T>(object parentInstance)
- {
- var serializedParent = JsonConvert.SerializeObject(parentInstance);
- return JsonConvert.DeserializeObject<T>(serializedParent);
- }
- }
- /////////////////////////// usage in MVC controller's action /////////////////////////////////////
- // Now I can initialize as -
- IMasterService<_ModelBaseMaster> mstrService = new RepositoryMaster<Master1>(context);
- // And finally -
- IEnumerable<_ModelBaseMaster> genericList = mstrService.FetchAll();
- //- this will prevent me from lengthy switch case for each master table
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement