FluentValidations:WithMessage 包含父数据?
FluentValidations: WithMessage to include parent data?
新手。
我有一项验证可确保订单的总销售额高于 0 美元。在错误消息中,我需要包含订单 ID。
像这样
RuleForEach(x => x.Orders).ChildRules(order =>
{
order.RuleFor(x => x.TotalSale)
.GreaterThan(0)
.WithMessage($"{order.orderId}: Total Sales must be greater than [=10=]");
如何访问验证中的“order.OrderId”?
使用提供对实例的访问的重载:
.WithMessage(o => $"{o.OrderId}: Total Sales must be greater than [=10=]");
documentation 中有一个关于它的片段:
工作 LINQPad 示例:
void Main()
{
var orders = new List<Order>();
orders.Add(new Order { OrderId = Guid.NewGuid(), TotalSale = 0 });
orders.Add(new Order { OrderId = Guid.NewGuid(), TotalSale = 5 });
orders.Add(new Order { OrderId = Guid.NewGuid(), TotalSale = 10 });
var customer = new Customer() { Orders = orders };
Console.WriteLine(customer);
var validator = new CustomerValidator();
var validationResult = validator.Validate(customer);
Console.WriteLine(validationResult.Errors.Select(x => x.ErrorMessage));
}
public class Customer
{
public List<Order> Orders { get; set; }
}
public class Order
{
public Guid OrderId { get; set; }
public Decimal TotalSale { get; set; }
}
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleForEach(x => x.Orders).ChildRules(order =>
{
order.RuleFor(x => x.TotalSale)
.GreaterThan(0)
.WithMessage(o => $"{o.OrderId}: Total Sales must be greater than [=11=]");
});
}
}
输出:
新手。
我有一项验证可确保订单的总销售额高于 0 美元。在错误消息中,我需要包含订单 ID。
像这样
RuleForEach(x => x.Orders).ChildRules(order =>
{
order.RuleFor(x => x.TotalSale)
.GreaterThan(0)
.WithMessage($"{order.orderId}: Total Sales must be greater than [=10=]");
如何访问验证中的“order.OrderId”?
使用提供对实例的访问的重载:
.WithMessage(o => $"{o.OrderId}: Total Sales must be greater than [=10=]");
documentation 中有一个关于它的片段:
工作 LINQPad 示例:
void Main()
{
var orders = new List<Order>();
orders.Add(new Order { OrderId = Guid.NewGuid(), TotalSale = 0 });
orders.Add(new Order { OrderId = Guid.NewGuid(), TotalSale = 5 });
orders.Add(new Order { OrderId = Guid.NewGuid(), TotalSale = 10 });
var customer = new Customer() { Orders = orders };
Console.WriteLine(customer);
var validator = new CustomerValidator();
var validationResult = validator.Validate(customer);
Console.WriteLine(validationResult.Errors.Select(x => x.ErrorMessage));
}
public class Customer
{
public List<Order> Orders { get; set; }
}
public class Order
{
public Guid OrderId { get; set; }
public Decimal TotalSale { get; set; }
}
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleForEach(x => x.Orders).ChildRules(order =>
{
order.RuleFor(x => x.TotalSale)
.GreaterThan(0)
.WithMessage(o => $"{o.OrderId}: Total Sales must be greater than [=11=]");
});
}
}
输出: