使用实体框架核心中的Fluent API编写范围数据注释

问题描述 投票:0回答:1

Description

当我正在尝试采用Clean Architecture时,我想摆脱数据注释并使用Fluent API,我个人开始更喜欢它。

但是,我不太擅长这种实现方式。

范围注释(旧方法)

我之前做的是使用Range注释来指定数字属性的最小值和最大值,如下所示:

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; }
}

这是我目前对Configuration类的看法:

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);
        }
    }
}

Questions

  1. 为此,Entity Framework Core中是否有内置的东西?
  2. 我应该以某种方式实现IValidatableObject界面吗?
  3. Configuration类应该关注其实体的验证吗?
c# asp.net-core entity-framework-core data-annotations clean-architecture
1个回答
1
投票

为此,Entity Framework Core中是否有内置的东西?

据我所知,没有Fluent API等同于RangeAttribute

我应该以某种方式实现IValidatableObject接口吗?

实现IValidatableObject不会使您使用Fluent API for RangeAttribute。你仍然需要使用DataAnnotation属性。

Configuration类应该关注其实体的验证吗?

IEntityTypeConfiguration旨在提供一种干净的方式来分离你的DbModel配置使用EntityFrameworkCore。因此,通常这样的配置类将包含模式级别设置和验证(约束,最大值,关系配置(在适当的情况下))。

你需要问自己的问题是为什么你甚至首先使用RangeAttribute。它没有任何模式方面的效果。您可以使用它,因为您还在构建的验证中使用实体类用于MVC。如果是这种情况并且您共享实体(POCO)类而不是为ViewModel或Dto提供单独的类,那么您将不得不使用混合版本,其中将与EF Core相关的数据注释分隔为IEntityTypeConfiguration类并保留数据注释用于MVC验证目的的属性。值得注意的是,就EF核心而言,DisplayNameAttribute也无关紧要。

© www.soinside.com 2019 - 2024. All rights reserved.