We have a Ticket
class which implements IValidatableObject
. It contains IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
method which performs object validation based on the private _action
property.
If _action
is ETicketAction.Create
, assignee must be null
; if action is ETicketAction.Edit
, assignee must not be null
. Besides these rules, we want to validate some common Ticket
fields (ProductLineId
, ProductVersion
). For this prupose, we implemented private ValidateCommonFields
method which is called from both create and edit actions.
public partial class Ticket : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrEmpty(Summary))
{
yield return new ValidationResult("Summary must be set!");
}
if (_action == (int)ETicketAction.Create)
{
if (Assignee != null)
{
yield return new ValidationResult("Assignee must be null when creating a ticket!");
}
ValidateCommonFields();
}
else if (_action == (int)ETicketAction.Edit)
{
if (Assignee == null)
{
yield return new ValidationResult("Assignee must be set when editing a ticket!");
}
ValidateCommonFields();
}
else if (_action == (int)ETicketAction.Close)
{
// ...
}
}
private IEnumerable<ValidationResult> ValidateCommonFields()
{
if (ProductLineId == null)
{
yield return new ValidationResult("Product line must be set!");
}
if (ProductVersion.IsNullOrEmpty())
{
yield return new ValidationResult($"Product version must be set!");
}
}
}
Debugger reaches the line where it calls ValidateCommonFields()
, but it never steps inside the function. We placed a breakpoint inside ValidateCommonFields
, but it is never hit. Both ProductLineId
and ProductVersion
are null, but the ValidationResult
s inside ValidateCommonFields
are not returned.
I assume it has something to do with the yield
statements. Should I use yield return ValidateCommonFields()
when calling the common validation method?