Entity Framework - provide a future date

We need to verify that the date stored in the table is a date in the future, is there a way to annotate the property, so the EF code can check and generate a db constraint first?

+4
source share
1 answer

Add a property attribute to your model, for example.

[DateInTheFuture] public DateTime ShippingDate { get; set; } 

and the attribute is the usual simple validation attribute:

 [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; } } 
+4
source

All Articles