Search code examples
asp.net-mvcdata-access-layer

MVC + 3 layer; DAL and viewmodels


I'm altering a normal 1-layer webshop into a 4-layer.

The problem is with DAL methods that return viewmodels or take viewmodels as parameter. Below is how I'm thinking but it won't work since DAL can't access viewmodels.

MVC: reference BLL and Model
    Controllers/
        CustomerController.cs
            [HttpPost]
            public ActionResult Create(CreateAccountViewModel c) {
                var logic = new CustomerLogic();
                logic.CreateAccount(c);
                return RedirectToAction("Success");
            }
    Views/Customer/
        CreateAccount.cshtml
    ViewModels/
        CreateAccountViewModel.cs

BLL: reference DAL, Model and MVC
    CustomerLogic.cs
        public void CreateAccount(CreateAccountViewModel c) {
            var db = new DBCustomer();
            db.createAccount(c);
        }

DAL: reference Model and BLL
    DBContext.cs
    DBCustomer.cs
        public void CreateAccount(CreateAccountViewModel c) {
            var db = DBContext;
            var newCust = new Customer() {
                FirstName = c.FirstName,
                LastName = c.LastName
            }
            db.Add(newCust);
        }

Model:
    Customer.cs

I'm following this diagram.


Solution

  • Your domain layer (Customer) should be defined in the Models library (the aside on the left). Then your BLL and DLL should reference the Models library and use this object for the business logic and persistence.

    Your view models should be converted to the Model instances at the presentation layer.