描述
当我尝试采用简洁的架构时,我想摆脱数据注释并使用Fluent API,就我个人而言,我开始喜欢更多。
但是,我不太擅长这种实现方式。
范围注释(旧方法)
我之前所做的是使用 Range
注释为数字属性指定 min 和 max,如下所示:
public class Engine
{
...
[Range(0, 10000)]
public int Size { get; set; }
[Display(Name = "Horse power")]
[Range(0, 1000)]
public int HorsePower { get; set; }
[Display(Name = "Top speed")]
[Range(0, 500)]
public int? TopSpeed { get; set; }
...
}
配置类(更简洁的方法)
现在,我尝试在与 Engine
实体关联的 Configuration 类中编写验证代码。
实体类:
public class Engine
{
public int EngineId { get; set; }
public int Size { get; set; }
public int HorsePower { get; set; }
public int? TopSpeed { get; set; }
public int FuelId { get; set; }
public int TransmissionId { get; set; }
}
这是我目前拥有的配置类:
using Carsurfer.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Carsurfer.Persistence.Configurations
{
public class EngineConfiguration : IEntityTypeConfiguration<Engine>
{
public void Configure(EntityTypeBuilder<Engine> builder)
{
builder.Property(engine => engine.Size);
}
}
}
问题
Entity Framework Core 是否为此内置了一些东西?
我是否应该以某种方式实现
IValidatableObject
接口(interface)?Configuration 类是否应该关注其实体的验证?
最佳答案
Is there something built in to Entity Framework Core for this?
据我所知,没有与 RangeAttribute
等效的 Fluent API。
Should I implement the IValidatableObject interface somehow?
实现 IValidatableObject
不会使您能够将 Fluent API 用于 RangeAttribute
。您仍然需要使用 DataAnnotation
属性。
Should the Configuration class be concerned with the validation of its entity?
IEntityTypeConfiguration
旨在提供一种整洁的方式来分离您的 DbModel
配置,供 EntityFrameworkCore
使用。因此,通常此类配置类将包含架构级别设置和验证(约束、最大值、关系配置(在适当的情况下))。
您需要问自己的问题是,为什么您首先要使用 RangeAttribute
。它对模式没有任何影响。您可能正在使用它,因为您还在构建验证中将实体类用于 MVC。如果是这种情况并且您共享您的实体 (POCO) 类而不是为您的 ViewModel 或 Dto 使用单独的类,那么您将不得不使用混合版本,在该版本中您将与 EF Core 相关的数据注释分离到 IEntityTypeConfiguration
类并将用于 MVC 验证目的的数据注释保留为属性。值得注意的是,就 EF Core 而言,DisplayNameAttribute
也是无关紧要的。
关于c# - 在 Entity Framework Core 中使用 Fluent API 编写范围数据注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55182438/