locked
add DBContext call to base controller RRS feed

  • Question

  • User1879907140 posted

    In my app, (using MVC CORE, EF), in all of my controllers I'm adding the following code:

    private readonly CarsContext _conn;
    
    public NewCarsController(CarsContext conn)
    {
       _conn = conn;
    }
    
    

    Is this the best way to call the Context or is there a way to add it to the home controller or basecontroller and call it once or should I keep the call in each controller? 

    Tuesday, June 16, 2020 5:55 PM

All replies

  • User1120430333 posted

    In my app, (using MVC CORE, EF), in all of my controllers I'm adding the following code:

    private readonly CarsContext _conn;
    
    public NewCarsController(CarsContext conn)
    {
       _conn = conn;
    }
    

    Is this the best way to call the Context or is there a way to add it to the home controller or basecontroller and call it once or should I keep the call in each controller? 

    IMHO, the controller should not be doing any direct database calls. You should be looking into implementing SoC.

    https://www.c-sharpcorner.com/UploadFile/1492b1/introduction-to-mvc-architecture-and-separation-of-concerns/

    Tuesday, June 16, 2020 6:04 PM
  • User475983607 posted

    Is this the best way to call the Context Model  or is there a way to add it to the home controller or basecontroller and call it once or should I keep the call in each controller? 

    Using a base controller works.

    There's not one answer to the question.   It depends on your design intention.  I rarely inject the DbContext directly in a controller.  Typically, I inject a service in the controller.  The service gets an injected DbContext.  

    Tuesday, June 16, 2020 6:07 PM
  • User1879907140 posted

    GeorgeTheCoder

    Is this the best way to call the Context Model  or is there a way to add it to the home controller or basecontroller and call it once or should I keep the call in each controller? 

    Using a base controller works.

    There's not one answer to the question.   It depends on your design intention.  I rarely inject the DbContext directly in a controller.  Typically, I inject a service in the controller.  The service gets an injected DbContext.  

    This is my first .NET CORE MVC app, so I'd like to follow the "standard", which varies on who you talk to. When I created the project using Visual Studio 2019, no base controller was created, only a home controller. 

    What do you mean by "Service"?  Micrsoservice, web service, etc.? 

    Tuesday, June 16, 2020 6:25 PM
  • User475983607 posted

    This is my first .NET CORE MVC app, so I'd like to follow the "standard", which varies on who you talk to. When I created the project using Visual Studio 2019, no base controller was created, only a home controller. 

    The result of an application design is typically several different design patterns.  It's up to you figure out what patterns are needed.  There is nothing wrong with injecting the DbContext into a controller but it does lead to code that is hard to test.

    What do you mean by "Service"? 

    A service is an API that adds a features to an application.   For example, a logger, cache, or business logic.   The official docs cover the details of registering services.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1

    Below are a few patterns which you might find useful.  

    https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-implemenation-entity-framework-core

    Tuesday, June 16, 2020 6:47 PM
  • User1120430333 posted

    GeorgeTheCoder

    mgebhard

    GeorgeTheCoder

    Is this the best way to call the Context Model  or is there a way to add it to the home controller or basecontroller and call it once or should I keep the call in each controller? 

    Using a base controller works.

    There's not one answer to the question.   It depends on your design intention.  I rarely inject the DbContext directly in a controller.  Typically, I inject a service in the controller.  The service gets an injected DbContext.  

    This is my first .NET CORE MVC app, so I'd like to follow the "standard", which varies on who you talk to. When I created the project using Visual Studio 2019, no base controller was created, only a home controller. 

    What do you mean by "Service"?  Micrsoservice, web service, etc.? 

    Follow the standards? That would be what one learns from tutorials, the too sweet cheese cake teaching,  he or she goes no further,   and they place everything in the controller. 

    MVC is about seperation of duty, and it's another form of seperation of concerns. 

    https://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

    https://en.wikipedia.org/wiki/Separation_of_concerns

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

    One should learn the layered style, which they are now starting to understand and ask about with posts even in the MSDN C# forum that is Windows form based,  along with starting to ask questions about MVP.

    using Microsoft.AspNetCore.Mvc;
    using PublishingCompany.Models;
    
    namespace PublishingCompany.Controllers
    {
        public class PayRollController : Controller
        {
            private IPayRollDM pdm;
            public PayRollController(IPayRollDM payRollDM)
            {
                pdm = payRollDM;
            }
            public IActionResult Index()
            {
                return View(pdm.GetAll());
            }
    
            public IActionResult Detail(int id = 0)
            {
                return id == 0 ? null : View(pdm.Find(id));
            }
    
            public ActionResult Create()
            {
                return View(pdm.Add());
            }
    
            [HttpPost]
            public ActionResult Create(PayRollVM.Payroll payroll, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
                
                if (!ModelState.IsValid) return View(pdm.PopulateSelectedList(payroll));
    
                if (pdm.BlnFindPayRollByAuthorId(int.Parse(payroll.AuthorTypeId)))
                {
                    ModelState.AddModelError(string.Empty, "Author has an existing PayRoll record.");
                }
    
                if (!ModelState.IsValid) return View(pdm.PopulateSelectedList(payroll));
    
                pdm.Add(payroll);
                return RedirectToAction("Index");
            }
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(pdm.Update(id));
            }
    
            [HttpPost]
            public ActionResult Edit(PayRollVM.Payroll payroll, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                if (!ModelState.IsValid) return View(payroll);
    
                pdm.Update(payroll);
                return RedirectToAction("Index");
            }
            public IActionResult Delete(int id = 0)
            {
                if (id > 0) pdm.Delete(id);
    
                return RedirectToAction("Index");
            }
    
            public ActionResult Cancel()
            {
                return RedirectToAction("Index", "Home");
            }
        }
    }

    Tuesday, June 16, 2020 8:36 PM
  • User-474980206 posted

    also in enterprise application (n-tier), typically the UI server is not allowed database access. The UI must call another service (behind a firewall) that actually has access to the database. Now days this is typically a micro-service. So my UI controllers are nothing but service calls. The service api is just injected.

      

    Tuesday, June 16, 2020 9:53 PM
  • User1879907140 posted

    also in enterprise application (n-tier), typically the UI server is not allowed database access. The UI must call another service (behind a firewall) that actually has access to the database. Now days this is typically a micro-service. So my UI controllers are nothing but service calls. The service api is just injected.

      

    That's my plan with this actually, though it' s an internal app, and I have experience with building WebAPI's, Web Services, etc. Once I get this completed, I'm then going to make all of the DB Calls in a MicroService

    Wednesday, June 17, 2020 11:03 AM
  • User-2054057000 posted

    In my app, (using MVC CORE, EF), in all of my controllers I'm adding the following code:

    private readonly CarsContext _conn;
    
    public NewCarsController(CarsContext conn)
    {
       _conn = conn;
    }
    

    Is this the best way to call the Context or is there a way to add it to the home controller or basecontroller and call it once or should I keep the call in each controller? 

    You can use Dependency Injection's AddSingleton() method so that  only a single object of CarsContext is used for all requests. This will saves a lot of memory.

    Thursday, June 18, 2020 4:48 AM