4

我们需要验证存储到表中的日期是未来的日期,有没有办法注释属性,以便 EF 代码首先可以验证并生成 db 约束?

4

1 回答 1

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;
    }
}
于 2012-12-21T18:07:03.473 回答