EF-是否需要两个字段之一? [英] EF - Require either of two fields?
本文介绍了EF-是否需要两个字段之一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以解决这个问题在做什么
(
,但我不想将其应用于整个类,而是只想将验证应用于类中的两个特定字段。
Is there a way to do what this question is doing (Either Or Required Validation) but instead of applying it on the entire class, I only want to apply the validation on two specific fields within the 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约束为一个或一个或一个条件。它们不能都为null。有办法吗?
I only want to constrain Bar1 and Bar2 to be an either/or requirement. They cannot both be null. Is there a way to do this?
推荐答案
您可以通过实现 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");
}
}
参考:
使用IValidatableObject与POCO进行更复杂的验证
这篇关于EF-是否需要两个字段之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文