实体框架 - 确保日期是将来的

时间:2012-12-21 17:51:04

标签: entity-framework validation .net-4.0

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

1 个答案:

答案 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;
    }
}