EF中索引数据注释的错误消息 [英] Error message for Index data annotation in EF

查看:110
本文介绍了EF中索引数据注释的错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Entity Framework 6.1.1,它支持其中的Index数据注释功能。
我的实体类中定义了一个字段:

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

这是正常的。不过,我试图找出当分数不是唯一的时候如何显示消息。现在它只是抛出一个异常。我尝试了以下

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

但它不包含此Index注释类的ErrorMessage的定义。
你能告诉我如何处理异常消息,以便它正常处理?

解决方案

IndexAttribute 不是一个验证属性,这就是为什么它没有ErrorMessage属性,它也没有用于验证它的IsValid()方法一个有效值的范围。



这意味着它不是像典型的验证属性(Required,MaxLength等)被设计为验证。 IsUnique 属性仅用于创建表创建时创建唯一索引。



如果要使用属性,则应创建自定义属性来检查索引的唯一性。该索引当然会继承 ValidationAttribute 类,并且必须在内部访问EF DbContext以检查属性验证码中的唯一性。



如果您不喜欢这种数据注释方法,并且它太复杂,那么您可以处理SaveChanges()方法抛出的 DbUpdateException 在try-catch块中,解码错误消息并返回您的视图模型中的一些友好。

  try 
{
using(var ac = new ApplicationDbContext())
{
//添加非唯一数据

ac.SaveChanges();
}
}
catch(DbUpdateException ex)
{
//处理索引错误
}
/ pre>

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?

解决方案

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
}

这篇关于EF中索引数据注释的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆