13

I created a new ASP.NET Core 2 MVC project in VS 2017 (version 15.5), changed user id type from string to Guid (also changed ApplicationUser class name to User), added my models and then

Add-Migration Init
Update-Database

but it generates error and database won't get created.

The object 'PK_AspNetUserTokens' is dependent on column 'UserId'.
ALTER TABLE ALTER COLUMN UserId failed because one or more objects access this column.

Here's my context:

public class ApplicationDbContext : IdentityDbContext<User, IdentityRole<Guid>, Guid>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<TvShow> TvShows { get; set; }
    public DbSet<Episode> Episodes { get; set; }
    public DbSet<Subscription> Subscriptions { get; set; }
    public DbSet<Notification> Notifications { get; set; }
    public DbSet<Genre> Genres { get; set; }
    public DbSet<TvShowGenre> TvShowGenre { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<Subscription>()
            .HasKey(c => new { c.TvShowId, c.UserId });

        builder.Entity<TvShowGenre>()
            .HasKey(c => new { c.TvShowId, c.GenreId });
    }
}

Here's my migration class (only up method):

public partial class Init : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropIndex(
            name: "UserNameIndex",
            table: "AspNetUsers");

        migrationBuilder.DropIndex(
            name: "IX_AspNetUserRoles_UserId",
            table: "AspNetUserRoles");

        migrationBuilder.DropIndex(
            name: "RoleNameIndex",
            table: "AspNetRoles");

        migrationBuilder.AlterColumn<Guid>(
            name: "UserId",
            table: "AspNetUserTokens",
            nullable: false,
            oldClrType: typeof(string));

        migrationBuilder.AlterColumn<Guid>(
            name: "Id",
            table: "AspNetUsers",
            nullable: false,
            oldClrType: typeof(string));

        migrationBuilder.AlterColumn<Guid>(
            name: "RoleId",
            table: "AspNetUserRoles",
            nullable: false,
            oldClrType: typeof(string));

        migrationBuilder.AlterColumn<Guid>(
            name: "UserId",
            table: "AspNetUserRoles",
            nullable: false,
            oldClrType: typeof(string));

        migrationBuilder.AlterColumn<Guid>(
            name: "UserId",
            table: "AspNetUserLogins",
            nullable: false,
            oldClrType: typeof(string));

        migrationBuilder.AlterColumn<Guid>(
            name: "UserId",
            table: "AspNetUserClaims",
            nullable: false,
            oldClrType: typeof(string));

        migrationBuilder.AlterColumn<Guid>(
            name: "Id",
            table: "AspNetRoles",
            nullable: false,
            oldClrType: typeof(string));

        migrationBuilder.AlterColumn<Guid>(
            name: "RoleId",
            table: "AspNetRoleClaims",
            nullable: false,
            oldClrType: typeof(string));

        migrationBuilder.CreateTable(
            name: "Genres",
            columns: table => new
            {
                Id = table.Column<long>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Genres = table.Column<int>(nullable: false),
                IsFirst = table.Column<bool>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Genres", x => x.Id);
            });

        migrationBuilder.CreateTable(
            name: "Notifications",
            columns: table => new
            {
                Id = table.Column<long>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                CreateDate = table.Column<DateTime>(nullable: false),
                Message = table.Column<string>(nullable: true),
                Seen = table.Column<bool>(nullable: false),
                UserId = table.Column<Guid>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Notifications", x => x.Id);
                table.ForeignKey(
                    name: "FK_Notifications_AspNetUsers_UserId",
                    column: x => x.UserId,
                    principalTable: "AspNetUsers",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateTable(
            name: "TvShows",
            columns: table => new
            {
                Id = table.Column<long>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                ProductionYear = table.Column<string>(nullable: true),
                Status = table.Column<int>(nullable: false),
                Title = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_TvShows", x => x.Id);
            });

        migrationBuilder.CreateTable(
            name: "Episodes",
            columns: table => new
            {
                Id = table.Column<long>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                BroadcastDate = table.Column<DateTime>(nullable: true),
                Duration = table.Column<TimeSpan>(nullable: true),
                Number = table.Column<int>(nullable: true),
                Season = table.Column<string>(nullable: true),
                Title = table.Column<string>(nullable: true),
                TvShowId = table.Column<long>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Episodes", x => x.Id);
                table.ForeignKey(
                    name: "FK_Episodes_TvShows_TvShowId",
                    column: x => x.TvShowId,
                    principalTable: "TvShows",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateTable(
            name: "Subscriptions",
            columns: table => new
            {
                TvShowId = table.Column<long>(nullable: false),
                UserId = table.Column<Guid>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Subscriptions", x => new { x.TvShowId, x.UserId });
                table.ForeignKey(
                    name: "FK_Subscriptions_TvShows_TvShowId",
                    column: x => x.TvShowId,
                    principalTable: "TvShows",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
                table.ForeignKey(
                    name: "FK_Subscriptions_AspNetUsers_UserId",
                    column: x => x.UserId,
                    principalTable: "AspNetUsers",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateTable(
            name: "TvShowGenre",
            columns: table => new
            {
                TvShowId = table.Column<long>(nullable: false),
                GenreId = table.Column<long>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_TvShowGenre", x => new { x.TvShowId, x.GenreId });
                table.ForeignKey(
                    name: "FK_TvShowGenre_Genres_GenreId",
                    column: x => x.GenreId,
                    principalTable: "Genres",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
                table.ForeignKey(
                    name: "FK_TvShowGenre_TvShows_TvShowId",
                    column: x => x.TvShowId,
                    principalTable: "TvShows",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateIndex(
            name: "UserNameIndex",
            table: "AspNetUsers",
            column: "NormalizedUserName",
            unique: true,
            filter: "[NormalizedUserName] IS NOT NULL");

        migrationBuilder.CreateIndex(
            name: "RoleNameIndex",
            table: "AspNetRoles",
            column: "NormalizedName",
            unique: true,
            filter: "[NormalizedName] IS NOT NULL");

        migrationBuilder.CreateIndex(
            name: "IX_Episodes_TvShowId",
            table: "Episodes",
            column: "TvShowId");

        migrationBuilder.CreateIndex(
            name: "IX_Notifications_UserId",
            table: "Notifications",
            column: "UserId");

        migrationBuilder.CreateIndex(
            name: "IX_Subscriptions_UserId",
            table: "Subscriptions",
            column: "UserId");

        migrationBuilder.CreateIndex(
            name: "IX_TvShowGenre_GenreId",
            table: "TvShowGenre",
            column: "GenreId");

        migrationBuilder.AddForeignKey(
            name: "FK_AspNetUserTokens_AspNetUsers_UserId",
            table: "AspNetUserTokens",
            column: "UserId",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);
    }
}

5 Answers 5

12

In your new Migration, just drop the keys before altering the columns and add the same keys back again afterwards.

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropPrimaryKey("PK_AspNetUserTokens", "AspNetUserTokens");
    migrationBuilder.DropPrimaryKey("PK_AspNetUserLogins", "AspNetUserLogins");
        
    ...
    migrationBuilder.AlterColumn<string>(...);
    ...

    migrationBuilder.AddPrimaryKey("PK_AspNetUserTokens", "AspNetUserTokens", new string[] { "UserId", "LoginProvider", "Name" });
    migrationBuilder.AddPrimaryKey("PK_AspNetUserLogins", "AspNetUserLogins", new string[] { "LoginProvider", "ProviderKey" });
}
1
  • 2
    @EKanadily MSSQL does not allow changing the type of a column that is the primary key. Removing it, changing the column, and then adding the primary key again works around this. It's probably because the index needs to be rebuild, values could no longer be unique in the new data type, etc.. Commented Sep 10, 2021 at 14:39
4

I faced same issue as you. I deleted my folder "Migration" and add migration again. Because of previous changes of migration, It wasn't able to create the FK accordingly.

4
  • 14
    Careful people... I followed this advice and my entire project crumbled. Do not just delete your migrations folder unless you back it up first. Or at least know what you are doing, but if you know what you are doing then you probably aren't reading this. (I don't know what I am doing btw)
    – Ryan
    Commented Jan 25, 2019 at 2:16
  • 1
    I don't think this is a good solution. It's gonna try to create table that is already in the database and it's gonna say it already exists :) Commented Jun 21, 2019 at 16:42
  • 6
    I'm not a big fan of downvoting. But this is not a solution. Say you have a project in production with multiple migrations. You cannot just delete the migrations folder. Commented Jul 26, 2019 at 7:01
  • Perfect Answer!!
    – El7or
    Commented Apr 11, 2020 at 7:17
2

I faced that error while Changing the DbContext Identity Schema. After checking AspNetUserTokens table it has a PK composed of 3 columns. I did the following workaround:

Drop the PK of AspNetUserTokens:

ALTER TABLE AspNetUserTokens DROP CONSTRAINT PK_AspNetUserTokens

You might face that error again on AspNetUserLogins, so same for this table:

ALTER TABLE AspNetUserLogins DROP CONSTRAINT PK_AspNetUserLogins

Then update-database hopefully it's Done.

Finally, add back the PKs:

ALTER TABLE AspNetUserLogins ADD CONSTRAINT PK_AspNetUserLogins PRIMARY KEY (LoginProvider,ProviderKey)
ALTER TABLE AspNetUserTokens ADD CONSTRAINT PK_AspNetUserTokens PRIMARY KEY ([UserId],[LoginProvider],[Name])
1

You have to rollback migrations till the last success one. Use dotnet ef migrations remove command for every failed migration.

1
  • I have the same issue, and went back with success but the error came back when I tried to Add-Migration again.. Commented May 20, 2020 at 9:08
0

I had the same error but for another Table and Columns, my error was: The object 'PK_AspNetUserTokens' is dependent on column 'LoginProvider'.

I am not sure if this is the correct way to do it in migrations but it worked for me.

I moved the migrationBuilder.AlterColumn<string>("LoginProvidertable: "AspNetUserLogins", to above migrationBuilder.AlterColumn<string>("Name","AspNetUserTokens

Did this for both Up and Down methods in the migration since I suspected that in the migration the table and column may be dependent on it in the batch job.

Also worth noting: I had no constraints in either of the tables so there might be something in older migrations causing this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.