Error message for Index data annotation in EF

我们两清 提交于 2019-12-04 09:19:27

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!