views:

443

answers:

2

I've started a project for school in which I am using ASP.NET MVC 2 + LINQ2SQL, and a business layer so my UI doesnt interact with the DB directly. My question is this:

In my MVC project, when bringing up views and passing around data, I still have to include my Data project for access to the classes in my Linq2Sql project. Is this correct?

Example:

Controller:

ClassesRepository cr = new ClassesRepository(); // this is from my Business project
Class classToEdit = cr.GetByClassId(id); // "Class" is from my data project

I still have to reference the Class class in my linq2sql data project - shouldn't my UI be completely independent of my data layer? Or maybe I'm going about this all wrong.

+2  A: 

I prefer to have my Repository do the mapping internally to my own classes. So what I return from my repository is not the LinqToSql classes but my own. I then map the returned classes data into a model for each views.

So it looks like:

LinqToSQL class -> MyClass (output from Repository at this point) -> (controller maps to model for a specific view) MyModel.

Make sure to always make a model for each view. You can just use what your repository returns but that is a short cut and mapping it to their own view models will pay off in the future.

Kelsey
When you say a model for each view, do you mean a model for the index, edit, create, view of a controller? Or in general a model for every object, that is manipulated with a controller? Right now I have a few view models I create to pass additional data along with my linq 2 sql classes.
Jack
I mean a model for each view. So yes an index, edit, create model etc... Map your linq2sql classes into your view models as the view models shouldn't be directly tied to the linqtosql models. Also you view models might not need all the data contained in the linqtosql or repository classes in every case.
Kelsey
Ahh I see, thank you much, very helpful. I guess my last question is, how does this prove pay off in the future? It just seems like more work to me (building wrapper models). With linq 2 sql i've got my validation attributes, I would then have to do the same for my view models.
Jack
Your decoupling your back end from your front end. This one of the main priniples of MVC and your just extending it to you data layer. If you ever want to swap out your back end you can easily just re-map you data layer to your class and the views and models don't need to change at all. Change one DLL and you done.
Kelsey
Great reason indeed :)
Jack
A: 

Take a look at the Golf Tracker Series at MVC Central, it does what you want and what Kelsey is describing.

http://www.mvccentral.net

Kahanu
Thanks for that link - your code is very clean. I'm going to do some refactoring on my test site to tidy up.
Jack