3

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?

Efi_K
  • 43
  • 5

1 Answers1

4

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");
David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
  • 2
    To get exactly what I wanted, I changed to: $"Name is not null and Description is null or Description is not null and Name is null", thanks. – Efi_K Jan 14 '21 at 02:12