As I'm trying to adopt Clean Architecture, I want to move away from Data Annotations and use Fluent API which, personally, I started to prefer a lot more.
However, I'm not too skilled in this way of implementing things.
What I was previously doing was to use the Range
annotation to specify a min and a max for number properties like so:
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; }
...
}
Now, I'm trying to write the validation code in the Configuration class associated with the Engine
entity.
The entity class:
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; }
}
This is what I currently have for the Configuration class:
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);
}
}
}
Is there something built in to Entity Framework Core for this?
Should I implement the IValidatableObject
interface somehow?
Should the Configuration class be concerned with the validation of its entity?
Is there something built in to Entity Framework Core for this?
There is no Fluent API equivalent to RangeAttribute
to the best of my knowledge.
Should I implement the IValidatableObject interface somehow?
Implementing IValidatableObject
won't enable you to use Fluent API for RangeAttribute
. You would still have to use DataAnnotation
attributes.
Should the Configuration class be concerned with the validation of its entity?
IEntityTypeConfiguration
is meant to provide a clean way to separate the your DbModel
configuration for EntityFrameworkCore
to use. So typically such configuration class will contain schema level set up and validation (constraints, max values, relational configuration (where appropriate)).
The question you need to ask yourself is why you are even using RangeAttribute
in the first place. It does not have any effect schema wise. You could be using it because you also use your entity classes for MVC in built validation. If that's the case and you share your entity (POCO) classes instead of having separate classes for your ViewModels or Dto's then you will have to just use a hybrid version where you separate data annotations that are EF Core related into IEntityTypeConfiguration
classes and leave data annotations that are for MVC validation purposes as attributes. It is worth noting that DisplayNameAttribute
is also irrelevant as far EF Core is concerned.