Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework EF-需要两个字段中的任何一个?_Entity Framework_Data Annotations - Fatal编程技术网

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

Entity framework EF-需要两个字段中的任何一个?,entity-framework,data-annotations,Entity Framework,Data Annotations,有没有办法解决这个问题 () 但是我不想在整个类上应用它,我只想在类中的两个特定字段上应用验证 比如说 public class FooModel { [Required] public string Name { get; set; } [Required] public decimal Cost { get; set; } public int Bar1 { get; set; } public float Bar2 { get; se

有没有办法解决这个问题 () 但是我不想在整个类上应用它,我只想在类中的两个特定字段上应用验证

比如说

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。有什么方法可以做到这一点吗?

我不认为您可以先通过代码来做到这一点!我认为您可以通过或通过使用存储过程/函数来实现这一点,这些存储过程/函数是通过在FooModel中插入来触发的。

您可以通过实现
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");
    }
}
公共类FooModel:IValidatableObject
{
[必需]
公共字符串名称{get;set;}
[必需]
公共十进制成本{get;set;}
公共int Bar1{get;set;}
公共浮动条2{get;set;}
公共IEnumerable验证(ValidationContext ValidationContext)
{
if(Bar1==null&&Bar2==null)
返回新的ValidationResult(“必须指定Bar1或Bar2”);
}
}
参考: