我正在尝试通过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用户成为SysAdmin,知道它不是权限问题....而且表格都在那里,包括它似乎爆炸的FK。
我很想运行我得到的sql脚本(在实际的SQL服务器上):
Update-Database -Script
然后做一个:
Add-Migration InitialCreate –IgnoreChanges
但是,我担心其他错误和障碍我不得不跳。非常感谢任何帮助。
答案 0 :(得分:7)
OnModelCreating
是这样做的地方,但您也希望利用此类迁移进行迁移。话虽如此,假设我们在OnModelCreating
中将更改添加到我们的“ApplicationDbContext”(使用默认项目名称):
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");
}
调用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
增加一些清晰度:
OnModelCreating
有它的目的,那就是让EF知道关系,密钥,实体到表的关系等.EF的迁移功能非常适合进一步发展并管理in - 数据库之间的状态,所以我希望尽可能利用它。
鉴于IdentityDbContext在其中有自己的声明,我们需要通过添加我们自己的OnModelCreating
来强调其配置(但仅在我们调用基本方法之后)。现在我们拥有所有现有的结构,但是有一个新名称。
引用您正在使用的实体也很重要。因此,由于默认项目使用ApplicationUser
,因此我们在modelBuilder.Entity<>()
中引用了此内容。
答案 1 :(得分:3)
如果你阅读上面的评论,这不仅仅是一个实际的解决方案。
首先(与上面的错误没有关系),部分重命名我的AspNetUsers表的代码丢失了,因此我的onModelCreating
函数的必要行也是如此:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("Users");
modelBuilder.Entity<ApplicationUser>().ToTable("Users"); //this line needed!!
modelBuilder.Entity<IdentityRole>().ToTable("Roles");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
}
即使在纠正之后,仍然使用错误的顺序生成必要的迁移代码,并且仍然抛出上述错误,在表已经重命名后引用旧表名。因此,我必须直接编辑迁移文件,并将DropForeignKey
方法移到RenameTable
方法之前的顶部:
public override void Up()
{
DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers");
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");
DropIndex("dbo.UserRoles", new[] { "UserId" });
DropIndex("dbo.UserClaims", new[] { "UserId" });
DropIndex("dbo.UserLogins", new[] { "UserId" });
AddColumn("dbo.UserRoles", "IdentityUser_Id", c => c.String(maxLength: 128));
AddColumn("dbo.Users", "Discriminator", c => c.String(nullable: false, maxLength: 128));
AddColumn("dbo.UserClaims", "IdentityUser_Id", c => c.String(maxLength: 128));
AddColumn("dbo.UserLogins", "IdentityUser_Id", c => c.String(maxLength: 128));
AlterColumn("dbo.UserClaims", "UserId", c => c.String());
CreateIndex("dbo.UserRoles", "IdentityUser_Id");
CreateIndex("dbo.UserClaims", "IdentityUser_Id");
CreateIndex("dbo.UserLogins", "IdentityUser_Id");
AddForeignKey("dbo.UserClaims", "IdentityUser_Id", "dbo.Users", "Id");
AddForeignKey("dbo.UserLogins", "IdentityUser_Id", "dbo.Users", "Id");
AddForeignKey("dbo.UserRoles", "IdentityUser_Id", "dbo.Users", "Id");
}
更改Update-Database
成功运行后。
我在www.asp.net/identity上观看了这个过程的视频教程,并在其上阅读了几个谷歌主管,我真的不知道为什么我的错误而且示例不是。我想我很幸运。但是,这是我的环境,以防它是一个错误:
接下来的问题......很快见到你们......
答案 2 :(得分:0)
首先。 在成功重命名默认IdentityUser表之前,将ApplicationUser类重命名为您希望的类。
因为ApplicationUser类继承自IdentityUser,并且是您的应用程序实际直接引用的用户配置文件问题。 因此,如果未更改,则使用与用户配置文件相关的onModelCreating()函数的表更改过程将提供引用,安全性或关系错误。
找到附加的更改截图,以便更了解我的观点。谢谢,我希望它能解决你的问题。
// Note this class is what i changed from ApplicationUser to just User
public class User : IdentityUser
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<User> manager)
{
.......... codes
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
base.OnModelCreating(modelBuilder);
// Rather than identityUser generic class , use the name of the renamed ApplicationUser being User
modelBuilder.Entity<User>().ToTable("User").Property(x => x.Id).HasColumnName("UserId");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogin");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaim").Property(x => x.Id).HasColumnName("ClaimId");
modelBuilder.Entity<IdentityRole>().ToTable("Role").Property(x => x.Id).HasColumnName("RoleId");
}
找到附加的更改截图,以便更了解我的观点。谢谢,我希望它能解决你的问题。