Efcore: Migrations: CHECK enum columns

Created on 19 Apr 2019  路  7Comments  路  Source: dotnet/efcore

closed-fixed good first issue type-enhancement

Most helpful comment

This is about adding a CHECK constraint to enum columns e.g.:
C# mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))

The easiest way of doing this is by adding a SqlServer convention (IModelFinalizedConvention) that calls AddCheckConstraint for all enum properties.

All 7 comments

hi @AndriySvyryd, Could you tell me which file i can add this CHECK?

This is about adding a CHECK constraint to enum columns e.g.:
C# mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))

The easiest way of doing this is by adding a SqlServer convention (IModelFinalizedConvention) that calls AddCheckConstraint for all enum properties.

Hi @AndriySvyryd

Find below my solution in the form of test case. Will it serve the purpose? Please add your comments.

`` [ConditionalFact] public void Can_create_check_constraint_with_enum() { var modelBuilder = CreateConventionModelBuilder(); var entityType = modelBuilder.Entity<Customer>().Metadata;

   modelBuilder
            .Entity<Customer>()
            .Property(t => t.EnumValue)
            .WithEnumConstraint();

   var checkConstraint = entityType.FindCheckConstraint("CK_Customer_EnumValue");

   Assert.NotNull(checkConstraint);
   Assert.Equal(entityType, checkConstraint.EntityType);
   Assert.Equal("CK_Customer_EnumValue", checkConstraint.Name);
   Assert.Equal("CHECK (EnumValue IN('Sun', 'Mon', 'Tue'))", checkConstraint.Sql);

}

@SARAVANA1501 Not quite, this should happen without needing to call WithEnumConstraint()

@AndriySvyryd ,

SqlServerEnumConstraintConvention

Please review the convention, and guide me to register it with other conventions,

Thanks.

You are heading in the right direction.

  • Call entityType.GetDeclaredProperties() instead of entityType.GetProperties() to avoid going over the same properties.
  • Don't call property.SetIsNullable(false)
  • The convention can be added in SqlServerConventionSetBuilder:
    C# ConventionSet.AddBefore( conventionSet.ModelFinalizedConventions, new SqlServerEnumConvention(), typeof(ValidatingConvention));
  • Add tests to EFCore.SqlServer.Tests

I'll give further feedback on the PR

Fixed in e17584c457a49c4dcd90fd5cf47cd3a61ae4db53

Was this page helpful?
0 / 5 - 0 ratings