0

Do we agree that adding validation atibutes just above auto generated POCOs entities (like with EF 4.x Dbcontext Generator template) is meaningless ?

Because each time the tool is ran, attributes are erased.

My question is : Is there a way to maintain both auto generated pocos entities one the one hand, and validation attributes on the other ?

Seems that it would be possible with a code first approach ?

Actually I sarted my project with a database first approach and auto generated my POCOs. Would it be possible to get rid of .tt files, keep generated pocos and use code first approach for managing new fields, validation attributes (and so on ...) ? Will the changes on POCOs update my database tables ?

Thanks a lot for your lights.

4

2 回答 2

1

If you are truly doing a "code first" approach, that means "the code is the boss". You shouldn't be running code generators repeatedly to update your code-- you should update POCOs directly yourself.

Of course, code-generating POCOs from a db at the start of a project can make sense, save a lot of work. But don't plan to keep doing it - you get the problems you mention.

If you wanted to do a "database first" approach, make changes in the db, and your POCOs will be a secondary thing, regenerated - kind of confusing as to who is "the boss".

So i think it makes sense to (as you say) "keep generated pocos and use code first approach for managing new fields, validation attributes (and so on ...)".

As to "Will the changes on POCOs update my database tables ?" - it shouldn't, unless you have something set to regenerate the db.

Note: i am coming from an NHibernate background, not EF, but the same concepts apply.

于 2012-04-12T17:31:56.977 回答
1

You have several problems here. The first is that you're trying to place validation attributes on your data model classes. This implies that you are passing your data objects directly to your views. While that works, it is not the recommended way to do it.

You should instead have View Models that have only the information needed for any given view, and these view models have your validation attributes. You then, in your business logic, map your view models to your data models.

However, if you're bound and determined to use your data models in your views, then you would use what are called "buddy classes" to add validators to metadata classes.

http://hartzer.wordpress.com/2010/01/26/mvc-buddy-class/

Finally, if you want to go to Code first, you will find that Code First works very differently than Database first. While you could take the generated entities and then map them to Code First mappings, it's much easier to use the Entity Framework Power Tools CTP1 to reverse engineer your database to a code first model, since this will also create your mappings.

于 2012-04-12T18:08:28.047 回答