Reputation: 3009
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.
Upvotes: 3
Views: 5370
Reputation: 1629
Data annotations are validator attributes that you need to add to the properties of the entity. There are number of standard attributes, or you can create custom ones if they don't satisfy your needs.
Upvotes: 2
Reputation: 28338
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:
public partial class Setting : INotifyPropertyChanging, INotifyPropertyChanged
{
// Auto-gen Properties, methods, etc go here.
}
This means you can have any number of other partial class Setting
fragments 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.
[MetadataType(typeof(SettingMetadata))]
public partial class Setting
{
}
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.
public class SettingMetadata
{
[Display(Name="Base Rate")]
[Required]
public decimal Rate
{
get;
set;
}
[Display(Name = "Permit Payments")]
public Boolean AllowPayments
{
get;
set;
}
[Display(Name = "Base URL For Web Service")]
[Required]
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Type must match linked metadata type.")]
public string WebServiceUrl
{
get;
set;
}
}
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.
Upvotes: 14