I want to use a validation anotation.
I have already a model implemented by entity framework.
I need data validation and I know that there is a data anotation which is very nice…
But I really don’t know how can I use it with entity framework correct.
Should I edit entities? Or should I write separated class? Or should I write class which are inherit from entities?
Can you tell me the best way I should use?
I want to write as few code as it is possible.
The way to handle this is a combination of partial classes and a special attribute that allows you to attach metadata to another class.
The entity framework already helps you out here by generating all classes as partial classes. So, if you had an entity in your model called Settings, the EF would create this:
This means you can have any number of other
partial class Settingfragments in other files, which the EF will not touch if/when you regenerate that code. If you want to add data validation attributes to this, it takes two steps:Attach a MetadataType attribute to the Setting class. There doesn’t need to be anything in the body of this partial class fragment, it’s only there to associate the attribute.
Create a second class that has the same public field names as the EF class, and associate whatever data validation attributes you want. The compiler will match up the metadata class fields with the EF class fields by name, and act as it whatever metadata is attached to your second class is also on your first class.
As mentioned in the FxCop suppression message, the name and type of the fields must match between the metadata class and associated class for this to work.