Skip to content

SqlServer Migrations: Rebuild check constraints #18965

Description

@Neme12

Steps to reproduce

  1. Start with:
using Microsoft.EntityFrameworkCore;
using System;

namespace ConsoleApp3
{
    public sealed class Record
    {
        public int Id { get; set; }
    }

    public sealed class ApplicationDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication-6E483A89-BEE6-4A76-96CC-CEB276E5E112;Trusted_Connection=True;MultipleActiveResultSets=true");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Record> Records { get; set; }
    }

    public static class Program
    {
        public static void Main()
        {
        }
    }
}
  1. Create a migration: Add-Migration Initial
  2. Add a property to Record and a check constraint that uses its column:
using Microsoft.EntityFrameworkCore;
using System;

namespace ConsoleApp3
{
    public sealed class Record
    {
        public int Id { get; set; }
+        public string Value { get; set; }
    }

    public sealed class ApplicationDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication-6E483A89-BEE6-4A76-96CC-CEB276E5E112;Trusted_Connection=True;MultipleActiveResultSets=true");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
+            modelBuilder.Entity<Record>().HasCheckConstraint("CK_Records_Value_NotEmpty", FormattableString.Invariant($"[{nameof(Record.Value)}] <> ''"));
        }

        public DbSet<Record> Records { get; set; }
    }

    public static class Program
    {
        public static void Main()
        {
        }
    }
}
  1. Create another migration: Add-Migration AddValue

In the generated migration, CreateCheckConstraint is called before AddColumn, resulting in a database error when applying the migration:

Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'Value'.

Generated migration:

using Microsoft.EntityFrameworkCore.Migrations;

namespace ConsoleApp3.Migrations
{
    public partial class AddValue : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateCheckConstraint(
                name: "CK_Records_Value_NotEmpty",
                table: "Records",
                sql: "[Value] <> ''");

            migrationBuilder.AddColumn<string>(
                name: "Value",
                table: "Records",
                nullable: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropCheckConstraint(
                name: "CK_Records_Value_NotEmpty",
                table: "Records");

            migrationBuilder.DropColumn(
                name: "Value",
                table: "Records");
        }
    }
}

This one is pretty easy to fix because we can just reorder the CreateCheckConstraint and AddColumn calls...

  1. Change the type of the new column:
using Microsoft.EntityFrameworkCore;
using System;

namespace ConsoleApp3
{
    public sealed class Record
    {
        public int Id { get; set; }
        public string Value { get; set; }
    }

    public sealed class ApplicationDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication-6E483A89-BEE6-4A76-96CC-CEB276E5E112;Trusted_Connection=True;MultipleActiveResultSets=true");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
+            modelBuilder.Entity<Record>().Property(r => r.Value).HasMaxLength(100);
            modelBuilder.Entity<Record>().HasCheckConstraint("CK_Records_Value_NotEmpty", FormattableString.Invariant($"[{nameof(Record.Value)}] <> ''"));
        }

        public DbSet<Record> Records { get; set; }
    }

    public static class Program
    {
        public static void Main()
        {
        }
    }
}
  1. Create another migration: Add-Migration ChangeValueType

In the generated migration, AlterColumn is called without first dropping and then recreating the check constraint, resulting in a database error when applying the migration:

Microsoft.Data.SqlClient.SqlException (0x80131904): The object 'CK_Records_Value_NotEmpty' is dependent on column 'Value'.

Generated migration:

using Microsoft.EntityFrameworkCore.Migrations;

namespace ConsoleApp3.Migrations
{
    public partial class ChangeValueType : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AlterColumn<string>(
                name: "Value",
                table: "Records",
                maxLength: 100,
                nullable: true,
                oldClrType: typeof(string),
                oldType: "nvarchar(max)",
                oldNullable: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AlterColumn<string>(
                name: "Value",
                table: "Records",
                type: "nvarchar(max)",
                nullable: true,
                oldClrType: typeof(string),
                oldMaxLength: 100,
                oldNullable: true);
        }
    }
}

This one is not at all easy to fix. I always have to look inside recent migrations to find the one where this check constraint was last created and then copy it to the new migration and add a corresponding DropCheckConstraint call. This really tideous, error-prone and time consuming if I there's a lot of check constraints.

I understand that there's no way for EF Core to understand what columns the SQL uses without parsing it. I have two ideas:

  1. Maybe all check constraints could be dropped and recreated if the migration alters any column? This would result in a lot of unnecessary recreations, but it should do the trick.
  2. Provide an optional (params) argument to manually specify all columns that the SQL affects. The API wouldn't be as easy to use (although a huge improvement over manually fixing up migrations) but it would be stable and reliable. The same approach could also be used for HasComputedColumnSql and HasDefaultValueSql, where issues have been reported many times before: Statement order in down-migration is incorrect #14030 Migrations does not properly work with calculated properties #12726 Migrations: Attempt better ordering when adding computed columns #6853

Further technical details

EF Core version: 3.0.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET Core 3.0
Operating system: Windows 10 Version 1903
IDE: Visual Studio 16.4.0 Preview 5.0

Activity

  1. added this to the 5.0.0 milestone on Nov 18, 2019
  2. bricelam commented on May 29, 2020

    @bricelam
    Contributor

    @roji was this fixed by #21040?

  3. bricelam commented on May 29, 2020

    @bricelam
    Contributor

    Ah, the second part (that we don't rebuild check constraints) is is still valid.

  4. changed the title [-]Check constraints wrong order with respect to columns in migrations[/-] [+]SqlServer Migrations: Rebuild check constraints[/+] on May 29, 2020
  5. roji commented on May 29, 2020

    @roji
    Member

    Yeah, the first one (ordering) should be fixed by #21040, but rebuilding is a different thing.

  6. modified the milestones: 5.0.0, Backlog on Jun 9, 2020
  7. removed their assignment
    on Jul 8, 2023
  8. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions