EF 自定义校验设置和捕获异常

时间:2023-04-18 08:03:55

一、定义

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))
}