1

With EntityFramework Core how can I limit a property to some values with the modelBuilder ?

In SQL it's :

CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))

Thanks,

2 Answers 2

2

You can use an enum

public enum Frequency
{
    Daily,
    Weekly,
    Monthly,
    Yearly
}

Then use EF Core value conversion with the EnumToStringConverter. This will work:

modelBuilder
   .Entity<Rider>()
   .Property(e => e.Mount)
   .HasConversion<string>();

It will not create the constraint in the database but it will put the enum type on the mapped property. If a bad value comes from the database it will map to the enum's default value.

Sign up to request clarification or add additional context in comments.

1 Comment

"it will not create the constraints" which is weird... 5.0.0-prerelease, for me, it did... but in 5.0.1 it's removing the constraints. Trying to figure out why.
0
List<string> str = new List<string>(){"Daily", "Weekly", "Monthly", "Yearly'}

in entity framework use Where

.Where(x=> str.Contains(x.Frequency ))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.