实体框架 - 对象“PK_AspNetUserTokens”依赖于列“UserId”

问题描述 投票:0回答:5

我在 VS 2017(版本 15.5)中创建了一个新的 ASP.NET Core 2 MVC 项目,将用户 id 类型从字符串更改为 Guid(还将 ApplicationUser 类名更改为 User),添加了我的模型,然后

Add-Migration Init
Update-Database

但它会生成错误并且不会创建数据库。

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

这是我的背景:

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 });
    }
}

这是我的迁移类(仅 up 方法):

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);
    }
}
asp.net sql-server entity-framework entity-framework-core asp.net-core-2.0
5个回答
10
投票

在新的迁移中,只需在更改列之前删除键,然后再次添加相同的键即可。

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" });
}

4
投票

我遇到了和你一样的问题。我删除了文件夹“迁移”并再次添加迁移。由于之前的迁移更改,无法相应地创建 FK。


1
投票

您必须回滚迁移,直到最后一次成功迁移。对于每次失败的迁移,请使用

dotnet ef migrations remove
命令。


1
投票

我在更改 DbContext 身份架构时遇到了该错误。检查

AspNetUserTokens
表后,它有一个由3列组成的PK。我做了以下解决方法:

放弃

AspNetUserTokens
的PK:

ALTER TABLE AspNetUserTokens DROP CONSTRAINT PK_AspNetUserTokens

您可能会在

AspNetUserLogins
上再次遇到该错误,因此此表也是如此:

ALTER TABLE AspNetUserLogins DROP CONSTRAINT PK_AspNetUserLogins

然后

update-database
希望是
Done.

最后,添加回PK:

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

0
投票

我不确定这是否是迁移中的正确方法,但它对我有用。

我把

migrationBuilder.AlterColumn<string>("LoginProvidertable: "AspNetUserLogins",
移到了上面
migrationBuilder.AlterColumn<string>("Name",table: "AspNetUserTokens

对迁移中的

Up
Down
方法都执行此操作,因为我怀疑在迁移中表和列可能在批处理作业中依赖于它。

还值得注意的是:我在这两个表中都没有任何约束,因此旧迁移中可能存在某些问题导致了这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.