Context

An EF Core enum stored as a string (HasConversion<string>()) was guarded by a CHECK constraint, so that a typo in a manual UPDATE fails at the database instead of breaking every later read:

[Mode] IN ('Off', 'AllowedDomainsOnly', 'Open')

Insight

  • The default collation accepts the wrong case. A migration test showed SQL Server accepted 'open'. Its default collation (e.g. SQL_Latin1_General_CP1_CI_AS) compares case-insensitively, so the “whitelist” accepts any casing.
  • The binary collation fixes SQL Server but breaks SQLite. COLLATE Latin1_General_100_BIN2 makes the check exact. If the model is also built with EnsureCreated on SQLite in unit tests, those tests fail with no such collation sequence: Latin1_General_100_BIN2.
  • Keep the constraint SQL Server-only. Declare it in OnModelCreating behind Database.IsSqlServer(), not in the shared IEntityTypeConfiguration. The migration snapshot is generated against SQL Server, so it still contains the constraint.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
if (Database.IsSqlServer())
{
modelBuilder.Entity<SettingsEntity>().ToTable("Settings", table =>
table.HasCheckConstraint(
"CK_Settings_Mode",
"[Mode] COLLATE Latin1_General_100_BIN2 IN ('Off', 'AllowedDomainsOnly', 'Open')"));
}
}

Always cover such a constraint with a migration test against a real SQL Server (e.g. Testcontainers) that tries a wrong-case value and a typo, and asserts the constraint name in the exception.

Often better: if the value only ever changes at deployment, keep it out of the database. Make it a configuration value bound to an enum, and fail at startup (ValidateOnStart) on an unknown value.