Search code examples
asp.net-mvc-3decoupling

MVC asp.net - should data access layer be decoupled from domain models?


If I follow decoupling all the way, it would appear that DataAccess layer should be de-coupled from models. But then passing the information to the data access layer becomes cumbersome...Instead of:

void Save(myModel modelObject) {
//db.Save here
}

I will do

void Save(string objectprop1,objectprop2...) {
}

Wouldn't that defeat the purpose of simplicity?

I think that passing a model to my data access layer is perfectly clean code, but then it's not de-coupled.


Solution

  • Your data access layer should certainly know about your domain models. You're right in thinking that breaking them apart into untold numbers of primitive arguments would be a very bad thing.

    De-coupling the DAL doesn't mean removing the dependency of the models from the DAL, but rather removing the dependency of the DAL from the models. The DAL can be represented, for example, by simple repositories:

    interface Repository<TModel> where TModel : BaseModel
    {
        TModel Get(int id);
        IEnumerable<Tmodel> Get();
        void Delete(int id);
        TModel Save(TModel model);
    }
    

    Or something of that nature, there are many ways to design it. The idea here is that the DAL is then free to store things in a different structure than the models represent. But from the perspective of the models, they're just persisting to repositories. The actual data persistence may be a different table structure (optimizing the database for performance without having to change the business models as a side-effect, for example) or even in multiple databases entirely.

    There's nothing wrong with the DAL knowing about the domain models. Indeed, as part of the domain, the DAL is expected to know about it. The models are central, the DAL is a back-end implementation which uses them.