Apply constraint through EF Core to SQL Server using .NET 6.0?

27 Views Asked by At

I am trying to apply database validation for a property from one of my tables. This is university project, so we are required to use code first. I am using Visual Studio 2022, the project is in .NET 6 and I am using EF Core 6 also.

So I have the property int YearFounded. I want to be between 1690 and 2024.

I thought about a [Range] data annotation, but if I'm not mistaken, the database doesn't understand it. So I looked around and tried this:

builder.Entity<Distillery>()
        .Property(e => e.YearFounded)
        .HasCheckConstraint("CK_Year_Min", "[YearFounded] >= 1500")
        .HasCheckConstraint("CK_Year_Max", "[YearFounded] <= 2024");

But I get this error:

Error CS1929 'PropertyBuilder<int>' does not contain a definition for 'HasCheckConstraint' and the best extension method overload 'RelationalEntityTypeBuilderExtensions.HasCheckConstraint(EntityTypeBuilder, string, string?)' requires a receiver of type 'Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder'

Is there a way to add check constraints from the entity and not from SSMS itself? Thanks a lot in advance!

0

There are 0 best solutions below