locked
How can I call the method in Datarepository from the controller RRS feed

  • Question

  • User-1355965324 posted

    Hi

    I have the following datarepository EmployeeManager  class

    EmployeeManager.cs
    namespace MyProject.GO.WebAPI.Services { public class EmployeeManager : IDataRepository<EmployeeModel, long> { GoContext ctx; public EmployeeManager(GoContext c) { ctx = c; } public IEnumerable<EmployeeModel> GetAll() { var employees = ctx.goEmployee.ToList(); return employees; } } }

    I want to call the method   GetAll() in my reportcontroller class to get all the employee name in a datatable  in report controller

    using MyProject.GO.WebAPI.Services;
    namespace MyProject.GO.UI.Controllers { public class ReportController : Controller { public IActionResult LeaversOverviewCriteria() {
    // I want to call GetAll() method here to get all the employees into a datatable , Please help
    return View(); } } }

    With Thanks

    Pol

    Thursday, October 24, 2019 7:47 AM

Answers

  • User475983607 posted

    The standard DI constructor pattern is shown below.   The Interface and startup.cs is not shown so there is no way to verify.

    using MyProject.GO.WebAPI.Services;
    namespace MyProject.GO.UI.Controllers
    {
    	public class ReportController : Controller
        {
    		private readonly IDataRepository<EmployeeModel, long> _repo;
    		
    		public ReportController(IDataRepository<EmployeeModel, long> repo) 
    		{
    			_repo = repo;
    		}
    
    		public IActionResult LeaversOverviewCriteria()
            {
    			var employees = repo.GetAll();
                return View();
            }
    
    	}
    }

    Be aware, Entity Framework is Unit of Work/Repository.  Your approach is actually an anti-pattern.  If you follow this path you'll end up creating a lot of extra code and have all kinds of problems.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 24, 2019 11:59 AM