【发布时间】:2019-03-01 19:35:34
【问题描述】:
考虑到这个简化的代码:
public class Request
{
public List<Selection> Selections { get; set; }
}
public class Selection
{
public decimal Price { get; set; }
}
public class RequestValidator(): AbstractValidator<Request>
{
public RequestValidator()
{
RuleForEach(x => x.Selections).SetValidator(new SelectionValidator());
}
}
public class SelectionValidator : AbstractValidator<Selection>
{
public SelectionValidator()
{
RuleFor(x => x.Price).NotEqual(0);
}
}
如果我有一个 Selection 项目,其中 Price 等于 0,我会收到错误消息:
'Price' must not be equal to '0'.
我缺少的是对集合中的哪个元素有此错误的引用。
调试时我可以清楚地看到Error.PropertyName 设置为Selections[0].Price,但格式化名称缺少对该项目的引用。
有没有办法正确格式化完整的属性名称?也许通过使用.WithMessage() 但它似乎不起作用。
为了清楚起见,我的目标是在嵌套项目上出现错误,如下所示:
<CollectionPropertyName>[<index>].<PropertyName> <error text>。前任。 Selectons[0].Price must not be equal to 0
【问题讨论】:
-
我不确定这是否可能。看看这个帖子,可能有用吗? stackoverflow.com/questions/27213058/…
标签: c# fluentvalidation