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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 19:42:33
Ladislav Mrnka

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.

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