我们需要验证存储到表中的日期是未来的日期,是否有办法注释属性,以便EF代码首先可以验证并生成数据库约束?
答案 0 :(得分:4)
在模型的属性上添加属性,例如
[DateInTheFuture]
public DateTime ShippingDate { get; set; }
,该属性是通常的简单验证属性:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class DateInTheFutureAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var futureDate = value as DateTime?;
var memberNames = new List<string>() { context.MemberName };
if (futureDate != null)
{
if (futureDate.Value.Date < DateTime.UtcNow.Date)
{
return new ValidationResult("This must be a date in the future", memberNames);
}
}
return ValidationResult.Success;
}
}