首页 > 解决方案 > 如何在干净架构的整个解决方案中定义相同的实体配置/验证

问题描述

在使用实体框架的基础设施层中,可以通过 IEntityTypeConfiguration 定义实体配置。

例如,引用 TodoList 实体

待办事项列表配置

public class TodoListConfiguration : IEntityTypeConfiguration<TodoList>
{
    public void Configure(EntityTypeBuilder<TodoList> builder)
    {
        builder.Property(t => t.Title)
            .HasMaxLength(200)
            .IsRequired();
    }
}

它将表列Title属性 长度设置为 200 个字符 (nvarchar(200)) 并将允许 null设置为 false。这意味着我们需要创建一个遵循这些约束的验证。这是由应用层中的两个验证器完成的(我使用的是 cqrs 模式)

CreateTodoListCommandValidator

public class CreateTodoListCommandValidator : AbstractValidator<CreateTodoListCommand>
{
    public CreateTodoListCommandValidator(IApplicationDbContext context)
    {
        RuleFor(v => v.Title)
            .NotEmpty()
            .MaximumLength(200)
    }
}

更新TodoListCommandValidator

public class UpdateTodoListCommandValidator : AbstractValidator<UpdateTodoListCommand>
{
    public UpdateTodoListCommandValidator(IApplicationDbContext context)
    {
        RuleFor(v => v.Title)
            .NotEmpty()
            .MaximumLength(200);
    }
}

可以看到,行为被指定了多次,代码被重复了3次

  1. TodoList 实体框架配置
  2. TodoList 创建验证器
  3. TodoList 更新验证器

问题会根据所需的验证而增加。

有没有人想出如何解决这个问题?

(我指的是https://github.com/jasontaylordev/CleanArchitecture repo)

标签: .net-coreclean-architecture

解决方案


在您的应用程序中多次出现相同的逻辑(在您的情况下是验证)意味着您有一个规范。

例如,在这里,您可以学习如何实现规范模式。


推荐阅读