简体   繁体   English

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

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

In my ASP.NET Core Web API Entity Framework Data Annotaion Code first, I have this code in DTO (Data Transformation Object):在我的 ASP.NET Core Web API 实体框架数据注释代码中,我在 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; }

How do I validate that EndDate must be greater than StartDate?如何验证 EndDate 必须大于 StartDate?

Thank you谢谢

Instead of auto-implemented properties you could use an instance variable and use the setter to check for yourself.您可以使用实例变量并使用 setter 自行检查,而不是自动实现的属性。

Also you could get some inspiration from Conditionally required property using data annotations您还可以使用数据注释从条件需要的属性中获得一些灵感

You can add custom validation logic by implementing the IValidatableObject on your DTO class.您可以通过在 DTO class 上实现IValidatableObject来添加自定义验证逻辑。 Aside from adding the interface to your class definition, add the following method:除了将接口添加到 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.");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Asp.net MVC Booked StartDate 和 EndDate 检查 - Asp.net MVC Booked StartDate and EndDate check ASP.NET MVC:如何将当前记录的StartDate放在较早记录的EndDate上 - ASP.NET MVC: How can I put the StartDate of a current record on the EndDate of an earlier record 如何使endDate的日期仅在startdate的日期之后选择 - How to make endDate's date choose only after startdate's date ASP.NET 如何使用 EF 内核在 Asp.net 内核 web API 中保存相关模型中的数据? - How to save Data in Related Models in Asp.net core web API using EF core? 如何在不使用EF的情况下连接ASP.NET Core Web API中的数据库? - How do I connect to database in ASP.NET Core Web API without using EF? 如何在ASP.NET Core 2 Web API中仅验证模型状态的一部分 - How to validate only a part of Model State in asp.net core 2 web api 如何验证模型取决于使用ASP.NET Core Web API的布尔数据类型值 - How to validate model depends on bool datatype value using asp.net core web api 如何有条件地验证 ASP.NET 核心 Web ZDB974238714CA8DE634A7CE1D08 中的整个 model? - How to conditionally validate entire model in ASP.NET Core Web API? 如何验证 asp.net 核心 3.0 web api 的获取请求中的参数? - How to Validate parameter in asp.net core 3.0 web api's get request? ASP.NET 内核 Web API - 如何使用数据注释根据指定值进行验证 - ASP.NET Core Web API - How to validate based on specified value using data annotation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM