C# EF:在Validate(ValidationContext ValidationContext)方法中无法访问复杂属性实例值
我有两门课 顾客 命令C# EF:在Validate(ValidationContext ValidationContext)方法中无法访问复杂属性实例值,c#,entity-framework,validation,C#,Entity Framework,Validation,我有两门课 顾客 命令 这里我缺少什么?如果您想使用自定义验证,请确保您的类继承了IValidatableObject。进行以下更改: public class Order : IValidatableObject // <-- Goes here { // Properties here } 您的订单类是否继承接口?因为您正在重写Validate方法,但您没有继承IValidateObject接口。是的,我为所有具有IValidateObject接口的实体提供了一个基类。在调试代
这里我缺少什么?如果您想使用自定义验证,请确保您的类继承了IValidatableObject。进行以下更改:
public class Order : IValidatableObject // <-- Goes here
{
// Properties here
}
您的
订单
类是否继承接口?因为您正在重写Validate
方法,但您没有继承IValidateObject
接口。是的,我为所有具有IValidateObject接口的实体提供了一个基类。在调试代码时,简单的属性验证正在工作,只有在上述复杂类型的场景中才会遇到问题。甚至导航集合都是为满足我的其他需求而加载的。能否显示OrderSvc.Update
的代码?
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;
}
}
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.
public class Order : IValidatableObject // <-- Goes here
{
// Properties here
}
if (ModelState.IsValid) {
// Write to db
}