ASP.NET Core Web API - 如何在 EF 中验证 EndDate 大于 StartDate

ASP.NET Core Web API - How to validate EndDate greater than StartDate in EF

在我的 ASP.NET Core Web API Entity Framework 数据注释代码中,我在 DTO(数据转换对象)中有此代码:

[DataType(DataType.Date)]
[Display(Name = "Start Date")]
[Required(ErrorMessage = "Start Date is Required")]
[JsonProperty(PropertyName = "StartDate")]
public DateTime StartDate { get; set; }

[DataType(DataType.Date)]
[Display(Name = "End Date")]
[Required(ErrorMessage = "End Date is Required")]
[JsonProperty(PropertyName = "EndDate")]
public DateTime EndDate { get; set; }

如何验证 EndDate 必须大于 StartDate?

谢谢

您可以使用实例变量代替 auto-implemented 属性,并使用 setter 自行检查。

你也可以从Conditionally required property using data annotations

中得到一些启发

您可以通过在 DTO class 上实施 IValidatableObject 来添加自定义验证逻辑。除了将接口添加到 class 定义之外,还添加以下方法:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    // if either date is null, that date's required attribute will invalidate
    if (StartDate != null && EndDate != null && StartDate >= EndDate)
        yield return new ValidationResult("EndDate is not greater than StartDate.");
}