开发者

How can I auto-generate DataValidation "Buddy" classes from my database in ASP.NET MVC3?

I have a website that has th开发者_StackOverflowe views generated directly from objects created by Entity Framework. After reading this blog by Scott GU it seems the best way to get DataValidation to work is to have started with POCO objects instead. (search for the word Buddy Class on the link)

Can I auto-generate my buddy classes somehow? Or did I start my foray into MVC on the wrong foot?


Or did I start my foray into MVC on the wrong foot?

I am afraid that this might be the case and the following sentence confirms it:

I have a website that has the views generated directly from objects created by Entity Framework

You shouldn't use your EF models in the views directly. It is considered good practice to have view models. Those are classes that are specifically designed to the needs of a given view and could contain formatting and validation. A typical scenario might be the following:

  1. A controller action is requested
  2. The controller queries the repository to fetch a model (EF model if you will)
  3. The controller converts this model into a view model using a mapping layer (this could be easily achieved with AutoMapper).
  4. The controller passes the view model to the view

This scenario works also when a controller action receives a view model from the view, checks whether the modelstate is valid, maps it back to a model and passes the model to a repository.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜