gpt4 book ai didi

entity-framework - EF - 需要两个字段中的任何一个?

转载 作者:行者123 更新时间:2023-12-05 01:21:15 29 4
gpt4 key购买 nike

有没有办法做这个问题正在做的事情( Either Or Required Validation )但我不想将它应用于整个类(class),我只想将验证应用于类(class)中的两个特定字段。

例如

public class FooModel {

[Required]
public string Name { get; set; }

[Required]
public decimal Cost { get; set; }

public int Bar1 { get; set; }

public float Bar2 { get; set; }
}

我只想将 Bar1 和 Bar2 限制为非此即彼的要求。它们不能都为空。有办法做到这一点吗?

最佳答案

您可以通过实现 IValidatableObject 添加服务器端验证

public class FooModel: IValidatableObject
{

[Required]
public string Name { get; set; }

[Required]
public decimal Cost { get; set; }

public int Bar1 { get; set; }

public float Bar2 { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Bar1 == null && Bar2 == null)
yield return new ValidationResult("Either Bar1 or Bar2 must be specified");
}
}

引用:

Using IValidatableObject with POCOs for More Complex Validations

关于entity-framework - EF - 需要两个字段中的任何一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20152757/

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