Reputation: 36156
Quick question on best practices.
I have one project MVC3 + razor that on my class, on each of my properties, I have some validations like these:
[StringLength(20)]
[RegularExpression(@"^[1-9][0-9]*$",ErrorMessage="Only Numbers Allowed") ]
[Required(AllowEmptyStrings = false, ErrorMessage = "Please Inform The Code")]
[Display(Name = "Code")]
public string gCode { get; set; }
This is on my, let's say, Customer class on my model. Validation works perfectly on the UI.
On a second project, when using Entity Framework - database first, I have my edmx file with my entities and I query the database using ObjectContext, which means the Customer class is built by EF.
Where am I supposed to add these validations now?
Upvotes: 2
Views: 493
Reputation: 4803
Model first has this problem - but it can be solved using MetaData. Say you have a generated entity called Field
and the Value field you want to decorate with a [Required]
attribute, just do the following:
namespace Model.Entities {
[MetadataType(typeof(FieldMetadata))]
public partial class Field : EntityBase {
}
class FieldMetadata {
[Required]
public object Value;
}
}
Here you are adding metadata to the Value member of an existing class's members that you cannot modify.
EDIT: If it doesn't work, make a call to the TypeDescriptor as well.
TypeDescriptor.AddProvider(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Field), typeof(FieldMetadata)), typeof(Field));
Upvotes: 3