首页 > 解决方案 > 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 可以吗?

标签: entity-frameworkentity-framework-coreef-fluent-apief-core-5.0

解决方案


您可以使用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");

推荐阅读