Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error message for Index data annotation in EF

Hi I am using Entity Framework 6.1.1 which supports the Index data annotation feature in it. I have a field defined in my entity class as:

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

This is working fine. However, I am trying to figure out how to display a message when the score is not unique. Right now it just throws an exception. I tried the following

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

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

like image 942
J. Davidson Avatar asked Oct 10 '14 17:10

J. Davidson


1 Answers

The IndexAttribute is not a validation attribute, and that is why it doesn't have the ErrorMessage property, and it also doesn't have the IsValid() method that is used to validate it against a range of valid values.

That means that it is not designed to be validated like the typical Validation attributes (Required, MaxLength etc.). The IsUnique attribute is just used during table creation to create an Unique Index.

If you want to use attributes, then you should create a custom attribute to check for uniqueness of the Index. That index would of course inherit the ValidationAttribute class, and would have to access the EF DbContext internally to check the uniqueness in the attribute validation code.

If you don't like this data-annotation approach, and it's too complex, then you can handle the DbUpdateException thrown by the SaveChanges() method in a try-catch block, decode the error message and return something friendly in your view-model.

try
{
    using (var ac = new ApplicationDbContext())
    {
        // Add non-unique data

        ac.SaveChanges();
    }
}
catch (DbUpdateException ex)
{
    // Handle index error
}
like image 149
Faris Zacina Avatar answered Oct 30 '22 03:10

Faris Zacina