According to my (perhaps incorrect) understanding business logic includes saving/updating entities in the database, as well as connecting with any 3rd party API's or using services and should therefore reside in the Model in MVC architecture. The controller should call model methods, and is responsible for application-wide logic, like authentication, some global data validation and response to the client.
Because I'm developing in C# I read the official Microsoft article recommendation:
Business logic should reside in services and classes within the Models folder.
However, in another Microsoft sample .NET project creating an entity is done directly in the controller (PostTodoItem
). So I'm wondering why isn't this code inside the model itself? In my opinion the model should contain the method AddTodoItem
which inserts a new todo item in the database. In theory adding an entity can be quite complex like validation, updating other models that's why I thought this code shouldn't reside directly in the controller.
EDIT: according to the link which @Christophe shared the repository pattern indeed offers an abstraction over data access layer. So in the repository pattern one would have:
public Buyer Add(Buyer buyer)
{
return _context.Buyers.Add(buyer).Entity;
}
where the controller would use the repository class Add()
instead of directly calling entiry framework's Add()
. The link also mentions that the repository pattern enables easier unit-testing because it's easier to mock repository methods than mock the context of entity framework. However, accessing context directly in the controller is also a valid option according to the same link.
Buyer
reference. It's always the same as thebuyer
input value. Whoever called that method clearly already has access to a reference to this object, because otherwise they wouldn't have been able to supply theBuyer buyer
parameter.