EF architecture--actual usage of FluentValidation

零下一度
Release: 2017-06-24 10:39:58
Original
1702 people have browsed it

Back to the directory

In MVC, EF, and LINQ environments, we often use DataModel (DO) and ViewModel (VO). We may use characteristics to verify their properties. Of course, this is very intuitive. Even Microsoft's DEMO is like this. It usually looks like this code

        /// <summary>/// 机构ID/// </summary>[DisplayName("机构ID")]public int AgentId { get; set; }/// <summary>/// 机构名称/// </summary>[DisplayName("机构名称")]
        [MaxLength(128)]public string AgentName { get; set; }/// <summary>/// 机构负责人/// </summary>[DisplayName("机构负责人")]
        [MaxLength(128)]public string AgentUser { get; set; }
Copy after login

. This design method will bring many problems to our future maintenance. The specific uncle summarizes Let’s look at:

  1. Mixed with data entities, without using extensions, the features you add may be lost when updating the entity

  2. If there are multiple VOs , then you need to add it to the specific VO, because the semantics of DO may not be clear

  3. It is not convenient for migration, and it is too highly coupled with ModelState

  4. From an object-oriented perspective, its responsibilities are too single and cause too many variables

To sum up, FluentValidation was born!

Go to nuget to install it: install-package FluentValidation

You can add multiple inspection classes to one of your entity classes, which is equivalent to having multiple inspection classes. Decorating an entity class, I think it’s pretty good!

   public class CreateUserEventValidator : AbstractValidator<CreateUserEvent>{public CreateUserEventValidator()
        {
            RuleFor(command => command.UserName).NotEmpty().Length(5, 20).WithMessage("用户名升序为5-20字符!");
            RuleFor(command => command.Email).NotEmpty().EmailAddress().WithMessage("不是有效的Email!");
            RuleFor(command => command.BirthDay).NotEmpty().Must(i => i < DateTime.Now).WithMessage("你的年紀太小了!");
        }
    }
Copy after login

When using it, you can get the information you need through IsValid, Errors and other attributes. Of course, you can also use it on command events and domain events, such as making a Verification decorator, which handlers need to be verified, just use this decorator to decorate it, it is very elegant!

   
   BusManager.Instance.Subscribe( ValidatorDecorator<CreateUserEvent>(
 UserEventHandler(),

   BusManager.Instance.Subscribe( LoggerDecorator<CreateUserEvent>( CreateUserEvent { UserName =  });
Copy after login

The decorator requires you to transfer an object to be decorated and a decorator, that’s it.

    /// <summary>/// 验证装饰器/// </summary>/// <typeparam name="TEvent"></typeparam>    [Serializable]public class ValidatorDecorator<TEvent>   : IBusHandler<TEvent>where TEvent : IBusData
    {/// <summary>/// 要被装饰的处理程序/// </summary>private readonly IBusHandler<TEvent> _inner;/// <summary>/// 校验装饰器集合/// </summary>private readonly IValidator<TEvent>[] _validators;/// <summary>/// 初始化/// </summary>/// <param name="inner">要被装饰的处理程序</param>/// <param name="validators">装饰器</param>public ValidatorDecorator(IBusHandler<TEvent> inner, params IValidator<TEvent>[] validators)
        {
            _inner = inner;
            _validators = validators;
        }public void Handle(TEvent evt)
        {var failures = _validators
                           .Select(v => v.Validate(evt))
                           .SelectMany(result => result.Errors)
                           .Where(error => error != null)
                           .ToList();if (failures.Any())
            {throw new ValidationException("实体校验失败", failures);
            }

            _inner.Handle(evt);
        }
    }
Copy after login

The learning and understanding of a kind of knowledge requires some theoretical foundation. You can read more books such as Design Module, Introduction to Algorithms, and .netCLR!

Thank you for reading!

The above is the detailed content of EF architecture--actual usage of FluentValidation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!