I have entity framework classes generated using the update from database option and model classes that I have created. My question is if I have a table called 'car' and have a model called 'car' as well what is the best way of using these? Should they be the same class or should I use partial or should I have separate class for the model and separate class to represent the database table can you point me to an example?
-
Duplicate of [MVC: Are Models and Entity objects separate concepts?](http://stackoverflow.com/questions/3819608/mvc-are-models-and-entity-objects-separate-concepts). – CodeCaster Oct 27 '13 at 01:39
2 Answers
I've always kept view models in a separate class library (with a separate namespace) from the entity data models. This way if the database schema changes (which almost always happens) I'm not breaking my views. And to move data between the data objects and view models I'm rather fond of Automapper. It'll even give you unit test failures if there are properties on a destination object that you are missing a source mapping for, helping you catch errors early.

- 7,728
- 1
- 25
- 39
-
Thats interesting I find myself writing code to map my model class to my entity framework generated class but they essentially contain very similar data and doing this didn't feel correct. – John Fleming Oct 27 '13 at 14:46
-
1In that scenario Automapper can make your life a lot easier. You can use your data models directly in the views, but that makes life more difficult as the project evolves. Another advantage of separate models is that if you have properties that really need to be protected from user modification (IsAdmin for example) you can easily prevent the user from modifying that through any kind of POST tampering when the models are separate. If you used the entities directly in the view, that kind of protection gets more complicated. – RyanR Oct 27 '13 at 14:53
-
Glad to help. Don't forget to [accept the answer](http://stackoverflow.com/help/accepted-answer) which helps the most. – RyanR Oct 27 '13 at 16:13
I've found it's normally good practice to have a separate project in your solution specifically for data access.
I normally set this up as a class library project with something similar to the following structure.
/ProjectNameData
/Models/ -- POCO's go here
/Mapping/ -- EntityTypeConfiguration classes go here
/Repositories/ -- Repositories go here
/ProjectContext.cs
Then I would have another class library for services as well as my main application project.

- 1,975
- 1
- 23
- 39