Search code examples
entity-frameworknon-nullable

EF6: migration generates nullable string despite IsRequired


I'm trying to generate a migration for a new Entity class that has a string field, called "Name". That string field should not be nullable.

I'm aware that "nullable" and "non-empty" are two different issues (see EF 6 IsRequired() allowing empty strings ). But for now I just want to stick to non-null.

I'm failing to achieve that. The generated migration always ends up having "nullable:true", as shown :

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Tags",
            columns: table => new
            {
                // ...
                Name = table.Column<string>(nullable: true),
                // ...
            },
            // ...
    }

I'm aware that I could achieve this with a annotation ( EF6 Add-Migration for not nullable string? ) but our architect forbade those. I need to stick to the Configure function in IEntityTypeConfiguration.

I'm using IsRequired().

public class TagEntityTypeConfiguration : IEntityTypeConfiguration<Tag>
{
    public void Configure(EntityTypeBuilder<Tag> builder)
    {
        builder.ToTable("Tag");

        builder.HasKey(x => x.Id);

        builder.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(100);

    }
}

Why do I get nullable:true despite .IsRequired ?


Solution

  • I was simply forgetting to use the EntityTypeConfiguration :

            modelBuilder.ApplyConfiguration(new TagEntityTypeConfiguration());
    

    Without this line the constraints are ignored.