EF - Require either of two fields?

旧巷老猫 提交于 2020-01-16 04:20:06

问题


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.

For example

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; }
}

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?


回答1:


You can add server side validation by implementing 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");
    }
}

Reference:

Using IValidatableObject with POCOs for More Complex Validations




回答2:


I do not think you can do that by code first! I think you can do that by validation or by used stored procedure / function which be triggered by the inserting in the FooModel. EF to AFTER INSERT Trigger



来源:https://stackoverflow.com/questions/20152757/ef-require-either-of-two-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!