MVC3 and EF Data first: what are the best practices?

邮差的信 提交于 2019-12-03 06:18:55

问题


It seems that most of the focus with MVC3 and EF4.1 is around "code first" - I can't seem to find any examples or tutorials that meet the following criteria:

  • uses an existing SQLServer database
  • has separate projects for web & data access (we will have multiple web apps sharing the same data access classes)
  • recommendations for validation

Does such an example or tutorial exist? Are there any documented "best practices" for how to accomplish this, or rationale for NOT having a solution structured this way?


回答1:


It is quite common scenario and it depends if you want to use EDMX file for mapping or if you want to have mapping defined in code (like code first).

Both scenarios can be done as database first

  • You will create EDMX from existing database with build in EF tools in Visual Studio and you will use DbContext T4 generator template to get POCO classes and DbContext derived class
  • You will download EF Power Tools CTP and you will use its reverse engineering feature to generate code mapping, POCO classes and context for you

Neither of these approaches will add Data annotations. Data annotations on entities should not be used for client validation (that is bad practice) unless you are doing very simple applications. Usually your views have some more advanced expectations and validation in view can be different then on entity. For example insert view and update view can need different validations and it is not possible to perform it with single set of data annotation on the entity. Because of that you should move data annotations for validation to specialized view models and transform your entities to view models and vice versa (you can use AutoMapper to simplify this).

Anyway it is possible to add data annotations to generated classes via buddy classes but as mentioned it is not a good practice.



来源:https://stackoverflow.com/questions/6585201/mvc3-and-ef-data-first-what-are-the-best-practices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!