generated from Avanade/avanade-template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ValidatorBase.cs
52 lines (46 loc) · 2.6 KB
/
ValidatorBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/CoreEx
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace CoreEx.Validation
{
/// <summary>
/// Represents the base entity validator.
/// </summary>
/// <typeparam name="TEntity">The entity <see cref="Type"/>.</typeparam>
public abstract class ValidatorBase<TEntity> : IValidatorEx<TEntity> where TEntity : class
{
/// <summary>
/// Gets the underlying rules collection.
/// </summary>
internal protected List<IEntityRule<TEntity>> Rules { get; } = [];
/// <summary>
/// Gets the <see cref="ExecutionContext.Current"/> instance.
/// </summary>
public CoreEx.ExecutionContext ExecutionContext => ExecutionContext.Current;
/// <summary>
/// Adds a <see cref="PropertyRule{TEntity, TProperty}"/> to the validator.
/// </summary>
/// <typeparam name="TProperty">The property <see cref="Type"/>.</typeparam>
/// <param name="propertyExpression">The <see cref="Expression"/> to reference the entity property.</param>
/// <returns>The <see cref="PropertyRule{TEntity, TProperty}"/>.</returns>
public virtual IPropertyRule<TEntity, TProperty> Property<TProperty>(Expression<Func<TEntity, TProperty>> propertyExpression)
{
PropertyRule<TEntity, TProperty> rule = new(propertyExpression);
Rules.Add(rule);
return rule;
}
/// <summary>
/// Adds a <see cref="PropertyRule{TEntity, TProperty}"/> to the validator.
/// </summary>
/// <typeparam name="TProperty">The property <see cref="Type"/>.</typeparam>
/// <param name="propertyExpression">The <see cref="Expression"/> to reference the entity property.</param>
/// <returns>The <see cref="PropertyRule{TEntity, TProperty}"/>.</returns>
/// <remarks>This is a synonym for <see cref="Property{TProperty}(Expression{Func{TEntity, TProperty}})"/> to enable <see href="https://docs.fluentvalidation.net/en/latest/">FluentValidation</see> syntax.</remarks>
public virtual IPropertyRule<TEntity, TProperty> RuleFor<TProperty>(Expression<Func<TEntity, TProperty>> propertyExpression) => Property(propertyExpression);
/// <inheritdoc/>
public virtual Task<ValidationContext<TEntity>> ValidateAsync(TEntity value, ValidationArgs? args, CancellationToken cancellationToken = default) => throw new NotSupportedException("Validate is not supported by this class.");
}
}