EF Core - 对多个属性添加约束,其中一个是必需的,但不是全部

问题描述

我有一个带有一些属性的类,我想对两个属性(int 类型)定义一个约束, 其中之一是必需的,但不是两者都需要。 在 sql 中它会是这样的:

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))

是否可以使用 FluentAPI?

解决方法

您可以使用HasCheckConstraint,例如

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");