一、定义
public class MyItem: IValidatableObject
{
[Key]
public long Id { get; set; }
[Range(0, 100, ErrorMessage = "企业客户收入占比必须在0-100之间")]
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (...)
yield return new ValidationResult("错误信息", new[] { "属性名称" });
}
}
二、捕获
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
==== ex.EntityValidationErrors.SelectMany(ii => ii.ValidationErrors).Select(ii => ii.ErrorMessage))
}