Saving data in MVC without Entity Framework?

asp.net asp.net-mvc c# dapper

Question

The majority of MVC examples I see seem to use Entity Framework. I am currently writing an MVC application that will not use EF (using Dapper instead) and I'm wondering where I should include the data persistence logic?

My first thought was to place it in along with the classes for my model. This would mean that my model classes would look something like below:

class User
{
   public int id {get; set;}
   public string name {get; set;}

   Create(string name)
   {
      // dapper to perform insert
   }

   Remove(int id)
   {
     // dapper to perform delete
   }

   //Update(),Delete() etc.
}

But I haven't used MVC much so I'm not sure if this is a common practice or not.

Is placing data persistence logic in with the Model a good practice or should I be taking a different approach?

Also, I believe that Stack Exchange uses MVC and Dapper - if anyone knows of anywhere that they have spoken about how they structured their code, feel free to point me towards it.

Accepted Answer

You wouldn't expect to have to open your computer and press a button on the harddrive to save data to it would you?

Basically the purpose of the MVC pattern, and SOLID design principles in general, is to separate your concerns. Putting logic related to saving, modifying or updating your database inside of your model, whose responsibility is to be an object that contains data, is counter to the philosophy of the pattern you're supposed to subscribe to in MVC.

Your controller is where you want to perform the logic to save your information, but there is still a data access layer that the concern of interacting with the database is abstracted to.

So you would have:

public class MyController {
    IDataAccessLayer _dataAccessLayer;

    public MyController(IDataAccessLayer dataAccessLayer) {
        _dataAccessLayer = dataAccessLayer;
    }
    public ActionResult Create(Model myModel){
        _dataAccessLayer.InsertIntoDatabase(myModel);
        return View();
    }
}

Popular Answer

As per design of MVC persistence never be a problem. You can use any ORM you want. For MVC pattern to work you need Model ( partial ViewModel) to display your data in View. Controller will handle your flow of application.

Now from controller you can call any process to save your data.

I think you can use Repository pattern with Dapper as well same as EF.

Main thing to take care that your application should not be persistence aware. You can develop with Dapper and later you can also provide support for EF without much changing at your UI level.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why