gpt4 book ai didi

entity-framework - Entity Framework - 确保日期是将来的日期

转载 作者:行者123 更新时间:2023-12-03 07:23:44 25 4
gpt4 key购买 nike

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

最佳答案

在模型的属性上添加属性,例如

[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;
}
}

关于entity-framework - Entity Framework - 确保日期是将来的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13994879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com