.net-core - 如何在干净架构的整个解决方案中定义相同的实体配置/验证
问题描述
在使用实体框架的基础设施层中,可以通过 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次
- TodoList 实体框架配置
- TodoList 创建验证器
- TodoList 更新验证器
问题会根据所需的验证而增加。
有没有人想出如何解决这个问题?
(我指的是https://github.com/jasontaylordev/CleanArchitecture repo)
解决方案
在您的应用程序中多次出现相同的逻辑(在您的情况下是验证)意味着您有一个规范。
推荐阅读
- docker - nginx-ingress 在 pod 中向 nginx 发送流量但不返回资产
- .net - .NET Hangfire,特定于作业的数据库连接
- php - PHP在返回值之前循环遍历一个函数
- unity3d - 统一着色器从蒙版中减去纹理
- eclipse - TestNG 框架 Eclipe - log().all() 未正确收集 Json 响应
- excel - 如果该行的相邻列中的日期在指定范围内,我需要计算“LOI-”在某个范围内出现的次数
- python - 烧瓶stderr打印到文件
- angular - 错误:调用 Firebase https 可调用云函数时在新 HttpsErrorImpl 内部出现错误
- c# - 我需要使用 Visual Studio 中的代码 C# 从表值函数中的 SQL 获取数据集
- c# - 如果没有引用任何项目,则 SQL 删除