asp.net-mvcentity-framework-4viewmodelmodelmetadatadata-annotations

How to override Entity Framework validation error messages


I have an Entity Framework 4.1 model that supports multiple ASP.NET MVC web applications. I use DataAnnotations to define and localize label text and validation rules and error messages.

For some applications, I need the label text for certain fields to differ from the standard, model-defined text. This is easy to achieve for the labels themselves: I retrieve the text I need from a local resource file, associated with the view. However, the label text is also used in validation error messages such as "{fieldname} must have a maximum length of 50 characters".

What is the best way to alter the validation messages without changing the Annotations on the model classes?


Solution

  • You have coupled your validation to your entity models. The way to avoid this is to create view models from your entities and put the validation on to those.

    Example: If you have the Entity...

    public class Product
    {
        public string Name {get; set;}
    }
    

    you could create two different view models:

    public class ProductPageViewModel1
    {
        [Required]
        public string Name {get; set;}
    }
    
    public class ProductPageViewModel2
    {
        [DisplayName("Foo")]
        public string Name {get; set;}
    

    }

    Map the entity to the view model and use these in your views.