Error message for annotating index data in EF

Hi I am using Entity Framework 6.1.1 which supports index data annotation function. I have a field defined in my entity class as:

[Index("scoreIndex", IsUnique=true)] public int score{ get; set; } 

It works great. However, I am trying to figure out how to display a message when the rating is not unique. Now it just throws an exception. I tried the following

  [Index("scoreIndex", IsUnique=true, ErrorMessage="Score must be unique")] 

But it does not contain an ErrorMessage definition for this Index annotation class. Could you tell me how to handle the exception message so that it handles it gracefully?

+5
source share
1 answer

IndexAttribute not a validation attribute, and therefore it does not have the ErrorMessage property, nor does it have the IsValid () method, which is used to validate it against a range of valid values.

This means that it is not intended to be validated as typical validation attributes (Required, MaxLength, etc.). The IsUnique attribute is used only when creating a table to create a unique index.

If you want to use attributes, then you must create a custom attribute to verify that the index is unique. Of course, this index inherits the ValidationAttribute class and will have to internally access the EF DbContext to verify the uniqueness of the attribute verification code.

If you don’t like this approach to data annotation and it is too complicated, you can handle the DbUpdateException by the SaveChanges () method in the try-catch block, decode the error message and return something friendly in your look model.

 try { using (var ac = new ApplicationDbContext()) { // Add non-unique data ac.SaveChanges(); } } catch (DbUpdateException ex) { // Handle index error } 
+2
source

Source: https://habr.com/ru/post/1204443/


All Articles