EF Core - Add constraint on multiple properties that one of them is required but not all

Viewed 381

I have a class with some properties and I want to define a constraint on two properties (int type), that one of them is required but not both. In SQL it will like this:

ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name> CHECK
((<first_field> IS NOT NULL AND <second_field> IS NULL) OR
(<second_field> IS NOT NULL AND <first_field> IS NULL))

Is it possible with FluentAPI?

1 Answers

You can use HasCheckConstraint, eg

modelBuilder.Entity<Customer>().Property(p => p.Name).HasColumnName("Name");
modelBuilder.Entity<Customer>().Property(p => p.Description).HasColumnName("Description");
modelBuilder.Entity<Customer>().HasCheckConstraint("ck_NameOrDescription", $"Name is not null or Description is not null");
Related