0

This is my first time using Entity Framework and I need to globalize validation messages.

As for now, the best approach that I've found is using something like this:

Entity

public class Entity
{
    [Display(Name = "Entity_Field", ResourceType = typeof (Resources))]
    [StringLength(128, ErrorMessageResourceType = typeof (Resources), ErrorMessageResourceName = "StringLengthMessage")]
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof (Resources), ErrorMessageResourceName = "RequiredMessage")]
    public string Field { get; set; }

}

Resources

| Name                | Value                               | Comment |
|:-------------------:|:-----------------------------------:|:-------:|
| Entity_Field        |Field Name                           |         |
| RequiredMessage     |{0} is required                      |         |    
| StringLengthMessage |{0} maximum length is {1} characters |         |

As you can see, using this strategy will force me to write a lot of repeated code and make the code harder to read (a very personal opinion).

I was looking for something more like this:

App.conf Using default message keys as in here

<entityFramework>
    <defaultErrorMessageResourceType>Project.Properties.Resources</defaultErrorMessageResourceType>
</entityFramework>

Entity

public class Entity {

[StringLength(128)]
[Display(Name = "Entity_Field")]
[Required(AllowEmptyStrings = false)]
public string Field { get; set; }

}

Resources

| Name                                  | Value                               | Comment |
|:-------------------------------------:|:-----------------------------------:|:-------:|
| Entity_Field                          |Field Name                           |         |
| RequiredAttribute_ValidationError     |{0} is required                      |         |    
| StringLengthAttribute_ValidationError |{0} maximum length is {1} characters |         |
Community
  • 1
  • 1
  • Those attributes `DisplayAttribute`, `StringLengthAttribute`, `RequiredAttribute` have nothing to do with Entity Framework. It happens that your EF model and your MVC View model are the same class. Your question is for MVC and globalization, not EF. I will update your question tag. – Igor Jun 22 '16 at 17:52
  • There are fluent libraries out there for asp.net mvc validation like [this one](https://fluentvalidation.codeplex.com/wikipage?title=mvc). This might be what you are looking for, it would allow you to use Reflection to add standard validation messages/resources to your models. – Igor Jun 22 '16 at 17:56
  • I decided to implement my own solution instead of trying to customize the built-in mechanism- this probably saved me many hours. – Rob Jun 22 '16 at 18:09

0 Answers0