Search code examples
c#asp.net-mvcentity-framework-6.1multi-layer

How to create data access layer in mvc application


I have a requirement to create register-login application with mvc and this application needs to be multilayered.

I don't know so much about the multi layer architecture, i have just read about it few times. So i believe in a standart mvc application:

Presentation layer - my views Bussiness layer - Controls

and where should i put my data access layer? In my application when user clicks register, model comes into action. I check if the model is valid, put it into the database using entity framework and redirect user to welcome page but data access layer is missing in this architecture.

Where should i put my data access and what responsibilities i should give to it?

For example, should i move all entity framework code into some other class or just move the code that is putting user into database to model itself?


Solution

  • You can create a separate project as the Data Access Layer. Connect it to a database and use EF in this project, and write classes to perform all the business operations using EF. You can also decouple the business logic from the actual database access logic, and place them in separate projects, but I think this is unnecessary as the EF itself is an ORM, and has all the data access logic.

    Now, reference this project in your MVC project, in which the views are your Presentation Layer. The models could be viewmodels or business models. In any case, you need to manage the conversion between the presentation layer and the business layer. Do not do this in the controller. Create a separate converter class to do this, following the 'Fat Model, Skinny Controller' philosophy of MVC.