EF:在Validate(ValidationContext validationContext)方法中无法访问复杂属性实例值

时间:2014-06-09 18:24:21

标签: c# entity-framework validation

我有2个班级

客户

    public class Customer {
    public bool PORequired { get; set; }
}

顺序

public class Order {
    public string PONumber { get; set; }
    public Customer CustomerInstance { get; set; }

    public override IEnumerable<ValidationResult> 
                       Validate(ValidationContext validationContext)
    {
        if (CustomerInstance.PORequired && string.IsNullOrEmpty(PONumber))
        {
            AddValidationError(new ValidationResult("PO is mandatory 
                                         in Orders for this Customer"));
        }
        return ValidationErrors;
    }
}

在Order类中,我正在尝试进行上面给出的验证,但无法访问CustomerInstance,因为它为null。

在验证之前,通过EF代码,我使用客户信息从数据库填充对象,但是当它通过验证上下文时,它似乎是空的。

OrderSvc.PopulateFromDatabase(order); //Populate the object from DB.
order.PONumber = "";                  // Setting the PONumber as blank for testing.
OrderSvc.Update(order); // Here order object has CustomerInstance with all the values.
OrderSvc.SaveChanges(); // In the next line, the validation method throws error that    customerinstance is empty.

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

如果要使用自定义验证,请确保您的类继承 IValidatableObject 。进行以下更改:

public class Order : IValidatableObject // <-- Goes here
{
   // Properties here
}

确保在尝试写入数据库之前调用 ModelState.IsValid

if (ModelState.IsValid) {
   // Write to db
}