Search code examples
data-access-layerdapper

Dapper and DAL Where must i place my validation


I am started with my first Dapper Dal project.

I have three projects: - Website (MVC) - DataLayer (Dapper) - Model (Poco Classes)

I want to add validation to my model but i also want to use clean poco classes for my datalayer. My datalayer use dapper to map my poco classes to the database.

I have searched the internet but i can't find a good answer.

My question is: Where do i add my validation? - In a seppetated project with classes that extend my poco classes or is there a different way?


Solution

  • If you want a clean separation between your DAL classes and your MVC classes, then you can do just that by, for instance, using ViewModels in your MVC-project. The ViewModel would have the properties and validations that works best with what you are presenting in the browser. Your controller would be responsible for mapping the data between the DAL classes and the ViewModels. Automapper is a very good tool for just that.

    It would look a bit like the following:

    DAL:

    public class MyDapperClass
    {
        public int Id { get; set; }
        public string SomeProperty { get; set; }
    }
    

    ViewModel:

    public class MyViewModelClass
    {
        public int Id { get; set; }
    
        [StringLength(50),Required]
        public string SomeProperty { get; set; }
    }
    

    Controller:

    // using AutoMapper;
    public class MyController : Controller
    {
        public MyController()
        {
            // Set up AutoMapper to be able to map your class
            Mapper.CreateMap<MyDapperClass, MyViewModelClass>();
        }
    
        public ActionResult MyAction()
        {
            var dalObject = DAL.GetObject();
            var viewModel = Mapper.Map<MyViewModelClass>(dalObject);
    
            return View(viewModel);
        }
    }