重命名 Identity 表并导致 EF6 迁移失败

2024-04-01

我正在尝试通过 EF6/Package Manager 中的迁移工具重命名我的 Identity 2.0 表。然而,它已经炸毁了一部分。我只是在 IdentityModels.cs 中的“ApplicationDBContext Create”之后调用以下代码:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<IdentityUser>().ToTable("Users");
            modelBuilder.Entity<IdentityRole>().ToTable("Roles");
            modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
            modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
            modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
        }

然后它会抛出这个错误:

PM> Update-Database -Verbose
Using StartUp project 'ProjectSender'.
Using NuGet project 'ProjectSender'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'Projectsender' (DataSource: x.x.x.x, Provider: System.Data.SqlClient, Origin: Configuration).
Applying explicit migrations: [201505080059533_RenameTables].
Applying explicit migration: 201505080059533_RenameTables.
EXECUTE sp_rename @objname = N'dbo.AspNetRoles', @newname = N'Roles', @objtype = N'OBJECT'
IF object_id('[PK_dbo.AspNetRoles]') IS NOT NULL BEGIN
    EXECUTE sp_rename @objname = N'[PK_dbo.AspNetRoles]', @newname = N'PK_dbo.Roles', @objtype = N'OBJECT'
END
Caution: Changing any part of an object name could break scripts and stored procedures.
Caution: Changing any part of an object name could break scripts and stored procedures.
EXECUTE sp_rename @objname = N'dbo.AspNetUserRoles', @newname = N'UserRoles', @objtype = N'OBJECT'
IF object_id('[PK_dbo.AspNetUserRoles]') IS NOT NULL BEGIN
    EXECUTE sp_rename @objname = N'[PK_dbo.AspNetUserRoles]', @newname = N'PK_dbo.UserRoles', @objtype = N'OBJECT'
END
EXECUTE sp_rename @objname = N'dbo.AspNetUserClaims', @newname = N'UserClaims', @objtype = N'OBJECT'
IF object_id('[PK_dbo.AspNetUserClaims]') IS NOT NULL BEGIN
    EXECUTE sp_rename @objname = N'[PK_dbo.AspNetUserClaims]', @newname = N'PK_dbo.UserClaims', @objtype = N'OBJECT'
END
EXECUTE sp_rename @objname = N'dbo.AspNetUserLogins', @newname = N'UserLogins', @objtype = N'OBJECT'
IF object_id('[PK_dbo.AspNetUserLogins]') IS NOT NULL BEGIN
    EXECUTE sp_rename @objname = N'[PK_dbo.AspNetUserLogins]', @newname = N'PK_dbo.UserLogins', @objtype = N'OBJECT'
END
IF object_id(N'[dbo].[FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[AspNetUserClaims] DROP CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
System.Data.SqlClient.SqlException (0x80131904): Cannot find the object "dbo.AspNetUserClaims" because it does not exist or you do not have permissions.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:c43cef2f-1614-40cc-a405-ecec90028871
Error Number:4902,State:1,Class:16
Cannot find the object "dbo.AspNetUserClaims" because it does not exist or you do not have permissions.

它是远程 SQL Server 2014 Express。然而,我暂时将我的 VS/sql 用户设置为系统管理员,以知道这不是权限问题......并且表都在那里,包括它似乎爆炸的 FK。

我很想运行我从(在实际的 SQL 服务器上)获得的 sql 脚本:

Update-Database -Script

然后做一个:

Add-Migration InitialCreate –IgnoreChanges

但是,然后我担心我将不得不跳过其他错误和障碍。任何帮助深表感谢。


OnModelCreating是执行此操作的地方,但您还想利用迁移来完成此类操作。话虽如此,假设我们将更改添加到our“ApplicationDbContext”(使用默认项目名称)内OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<ApplicationUser>().ToTable("Users");
    modelBuilder.Entity<IdentityRole>().ToTable("Roles");
    modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
    modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
    modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
}

Calling Add-Migration AspNetIdentity_RenameTables应该为我们生成迁移脚本(假设存在现有迁移来使用默认命名创建身份表):

public partial class AspNetIdentity_RenameTables : DbMigration
{
    public override void Up()
    {
        RenameTable(name: "dbo.AspNetRoles", newName: "Roles");
        RenameTable(name: "dbo.AspNetUserRoles", newName: "UserRoles");
        RenameTable(name: "dbo.AspNetUsers", newName: "Users");
        RenameTable(name: "dbo.AspNetUserClaims", newName: "UserClaims");
        RenameTable(name: "dbo.AspNetUserLogins", newName: "UserLogins");
    }

    public override void Down()
    {
        RenameTable(name: "dbo.UserLogins", newName: "AspNetUserLogins");
        RenameTable(name: "dbo.UserClaims", newName: "AspNetUserClaims");
        RenameTable(name: "dbo.Users", newName: "AspNetUsers");
        RenameTable(name: "dbo.UserRoles", newName: "AspNetUserRoles");
        RenameTable(name: "dbo.Roles", newName: "AspNetRoles");
    }
}

现在打电话Update-Database照顾其余的事情。显然,如果您使用 Migrate 初始化程序设置了 DbInitializer,那么这将在第一次加载时为您完成)。

现在,我们有了重命名的表:

可以在 GitHub 上找到示例(包含提交历史记录):https://github.com/bchristie/AspNetIdentity-RenameTables https://github.com/bchristie/AspNetIdentity-RenameTables


为了增加一些清晰度:

OnModelCreating有它的目的,那就是让 EF 了解关系、键、实体到表的关系等。EF 的迁移功能在更进一步并管理数据库的中间状态方面表现得非常好,因此我喜欢尽可能利用它。

鉴于 IdentityDbContext 有自己的声明,我们需要通过添加一个来超越它的配置OnModelCreating我们自己的(但只有在我们调用基本方法之后)。现在我们拥有了所有现有的结构,但有了新的名称。

提及与您合作的实体也很重要。因此,由于默认项目使用ApplicationUser,这就是我们要引用的内容modelBuilder.Entity<>().

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重命名 Identity 表并导致 EF6 迁移失败 的相关文章

  • 使用 CLR 返回表

    我想编写一个 CLR 过程 它接受一个文本并返回一个包含该文本中所有单词的表 但我不知道如何返回一张桌子 你能告诉我吗 Microsoft SqlServer Server SqlFunction public static WhatTyp
  • 发布时出错:System.DirectoryServices.DirectoryServicesCOMException

    我在我的 asp net MVC 解决方案中使用 AD 身份验证 它在本地服务器中工作 但是当我发布它时 我收到错误 System DirectoryServices DirectoryServicesCOMException 发生操作错误
  • 加密数据库字段的好方法?

    我被要求加密数据库中的各种数据库字段 问题是这些字段在读取后需要解密 我在用着Django and SQL Server 2005 有什么好主意吗 See 在 SQL Server 2005 数据库中使用对称加密 https web arc
  • SQL 2008全文索引填充延迟

    我的经理说 在基础表数据更改后 可能需要一段时间才能更新全文搜索索引 例如 如果我有一张桌子Products有一个柱子Description我更新了该描述 然后我可能需要一些时间才能搜索该新描述 真的吗 这需要多长时间 SQL 2008 对
  • Sequelize.js 中的自定义或覆盖连接

    我需要使用创建自定义连接条件Sequelize js http sequelizejs com使用 MSSQL 具体来说 我需要加入TableB基于一个COALESCE中的列的值TableA and TableB并最终得到这样的连接条件 L
  • 如何将 数组传递给存储过程

    我有一个清单索赔数据在 C 中 它有三个项目 日期 类型和描述 其中可以有多行 如下所示 索赔数据 Date Type Description 01 02 2012 Medical Its a medical 05 02 2013 Thef
  • Reporting Services 在哪里存储其日志文件

    最相关的谷歌结果似乎表明 为了访问日志 我们必须将您自己的日志表部署到数据库并制作报告服务写入它 http technet microsoft com en us library ms157403 aspx 简而言之 Reporting S
  • SQL返回两行之间的秒差

    这个问题与SQL Server有关 我有下表 id size batch code product code additiontime 1 91 55555 BigD Red 2017 05 15 13 00 00 2 91 55555 B
  • 同一索引操作上的不同估计行?

    简介和背景 我必须优化一个简单的查询 下面的示例 重写几次后 我认识到同一个索引操作的估计行数会根据查询的编写方式而有所不同 最初 该查询执行了聚集索引扫描 因为生产中的表包含二进制列 该表相当大 大约 100 GB 并且全表扫描执行起来需
  • 无法通过 LINQ to Entities 使用某些功能?

    我正在尝试使用 LINQ 查询在项目上实现搜索功能 由于数据有时包含带有重音符号和其他符号的字符 因此我创建了一种方法来删除这些字符以进行搜索 这是我的代码 var addresses from a in db Addresses join
  • 我应该对 ObjectContext 使用 using 关键字吗?

    我在这个网站或 CodeProject 的某个地方读到 好的规则是 如果某个类已经实现了 IDisposable 接口 那么您应该使用 using 关键字 因为使用翻译成 MSIL 的关键字会尝试 最终阻止如下内容 try some log
  • 起订量:无法投射到接口

    今天早些时候我问过这个question https stackoverflow com questions 2774785 moq unable to cast 因此 由于起订量从接口创建它自己的类 我无法将其转换为不同的类 所以这让我想知
  • 是否有适用于 SQL Server Express 的 SQL Server Profiler? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 是否有适用于 SQL Server Express 的 SQL Server Profiler 也许是开源的 或者也许只是一个可以帮助我查
  • Active Directory 会员资格提供商 - 如何对此进行扩展?

    我正在努力通过 AD Membership Provider 启动并运行 MVC 应用程序 但在解决这个问题时遇到了一些问题 我有一个基本配置设置并在我登录时工作 电子邮件受保护 cdn cgi l email protection 密码
  • EF代码首先从数据库0..1到多个关系

    我正在尝试从现有数据库生成实体框架代码优先模型 不更改数据库架构 该数据库过去曾用于生成 edmx 模型 我正在尝试使用 Fluent Api 或数据注释来实现等效模型 我无法使用连接表 不是可为空的外键 重现 0 1 到许多的关系 所以它
  • 使用 LINQ2SQL 在 ASP.NET MVC 中的各种模型存储库之间共享数据上下文

    我的应用程序中有 2 个存储库 每个存储库都有自己的数据上下文对象 最终结果是我尝试将从一个存储库检索到的对象附加到从另一个存储库检索到的对象 这会导致异常 Use 构造函数注入将 DataContext 注入每个存储库 public cl
  • DbContext 和 ObjectContext 有什么区别

    From MSDN 表示工作单元和存储库模式的组合 使您能够查询数据库并将更改分组在一起 然后将这些更改作为一个单元写回存储 DbContext在概念上类似于ObjectContext 我虽然DbContext只处理与数据库的连接以及针对数
  • SignalR 似乎正在减慢我的 MVC/Azure 应用程序的启动速度

    我有一个 MVC 应用程序在 Windows Azure 上的 WebRole 上的 NET 4 5 下运行 使用 SignalR 1 0 alpha2 并使用 ServiceBus 底板 在我的 App Start 文件夹中 我有 Reg
  • 如何通过SQL查询检查是否有JSON函数?

    有SQL 2016 中的 JSON 函数 https learn microsoft com en us sql t sql functions json functions transact sql例如 JSON VALUE JSON Q
  • 我是否需要在外键上指定 ON DELETE NO ACTION?

    我有以下与 SQL Server 2012 一起使用的 DDL CREATE TABLE Subject SubjectId INT IDENTITY 1 1 NOT NULL Name NVARCHAR 50 Not NULL CONST

随机推荐