C# MVC architecture, should I call stored procedures from MODEL or CONTROLLER

1.2k views Asked by At

I'm learning some stuffs about Model View Controller architecture, because I want to implement it in my project, so as much as I understand it goes like this:

M - Model, part of project where I add connection to database (LINQ TO SQL Classes or ADO.NET Entity for example)

V - View, part of project where I keep my forms if we are talking about c# windows form application

C - Controller, part of project where I'm writing methods for retrieving and inserting data from my forms to database, for example: if I want to select all customers from database I would do next:

public class CustomerController
{
   public static List<Customers> GetActiveCustomers()
   {
      return DataServices.DB.proc_SelectAllActiveCustomers().ToList();
   }
}

So in code above, in my controller, I am calling stored procedure called proc_SelectAllActiveCustomers, which will fill my form with All active customers if I call it from some of my forms..

So guys is this correct? Or I should call my stored procedures somehow from Model, or actually that's it because DataServices.cs is located in Model and it's used for opening connection to database?

I'm confused about this..

Could anyone explain me is this right or not?

Thanks guys, cheers!

3

There are 3 answers

2
David Libido On

Ideally, your model should do absolutely nothing. The controller should pass it to the view to render it and that's it. If a stored procedure needs to be used, you would do it in the controller.

0
Eldon Elledge On

The Controller is where all data functionality and other logic is done. The Controller should not connect directly to the database, but could have a database context injected into it. It would then request the needed data entities to populate the Model.

The Model has to logic of functionality. It is considered a Dumb Object or a DTO (Data Transfer Object). Based on what technologies you are using, it could contain Property Attributes that could be used when passed to the View for validation and formatting.

The View is used to display the model(s) you pass to it and receive any needed input. The View should have limited Logic or functionality based on what's required to put proper data in a model that can be returned back to the Controller for processing.

Hope this helps. Let me know.

0
ardalan ebrahimi On

"Model" is in charge just to transfer Data between "View" and "Controller" although sometimes it has some business logic(bad practice, it must be a completely mindless object) , but it should not have any dependency to business layer or data access layer.

fetched data must been called from the controller and by calling some kind of repository or service or etc. the "Controller" it is!

p.s. to avoid multiple instancing of a service/repository you can use a "Dependency Injection", go for it.