ASP.NET SimpleMembershipProvider 的自动迁移 [英] Automatic Migrations for ASP.NET SimpleMembershipProvider

查看:32
本文介绍了ASP.NET SimpleMembershipProvider 的自动迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我尝试在我的新 MVC 4 项目中使用自动迁移,但不知何故它不起作用.我 循序渐进地关注了这篇博文.

So I tried to use automatic migrations with my new MVC 4 Project but somehow it isn't working. I followed this blog post step by step.

我已将更改添加到 UserProfile 帐户模型(NotaryCode 字段):

I've added the changes to the UserProfile account model (the NotaryCode field):

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int NotaryCode { get; set; }
}

然后我在包管理器控制台上写enable-migrations,出现了一个Configuration类(继承自DbMigrationsConfiguration)然后我填充类如:

Then I wrote on the package manager console enable-migrations and a Configuration class appeared (inherits from DbMigrationsConfiguration<Web.Models.UsersContext>) then I fill the class as:

public Configuration()
{
    AutomaticMigrationsEnabled = true;
}

protected override void Seed(Atomic.Vesper.Cloud.Web.Models.UsersContext context)
{
    WebSecurity.InitializeDatabaseConnection(
            "DefaultConnection",
            "UserProfile",
            "UserId",
            "UserName", autoCreateTables: true);

    if (!Roles.RoleExists("Atomic"))
        Roles.CreateRole("Atomic");

    if (!Roles.RoleExists("Protocolista"))
        Roles.CreateRole("Protocolista");

    if (!Roles.RoleExists("Cliente"))
        Roles.CreateRole("Cliente");

    string adminUser = "randolf";

    if (!WebSecurity.UserExists(adminUser))
        WebSecurity.CreateUserAndAccount(
            adminUser,
            "12345",
            new { NotaryCode = -1 });

    if (!Roles.GetRolesForUser(adminUser).Contains("Atomic"))
        Roles.AddUsersToRoles(new[] { adminUser }, new[] { "Atomic" });
}

然后我尝试运行 update-database -verbose 但这不起作用.我的意思是,这是输出:

And then I tried to run update-database -verbose but this doesn't work. I mean, this is the output:

数据库中已经有一个名为UserProfile"的对象.

PM> update-database -verbose
Using StartUp project 'Web'.
Using NuGet project 'Web'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'VesperCloud' (DataSource: .SQLSERVER, Provider: System.Data.SqlClient, Origin: Configuration).
No pending code-based migrations.
Applying automatic migration: 201211051825098_AutomaticMigration.
CREATE TABLE [dbo].[UserProfile] (
    [UserId] [int] NOT NULL IDENTITY,
    [UserName] [nvarchar](max),
    [NotaryCode] [int] NOT NULL,
    CONSTRAINT [PK_dbo.UserProfile] PRIMARY KEY ([UserId])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'UserProfile' in the database.
   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)
   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.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
   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, XDocument targetModel, IEnumerable`1 operations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
   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.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
ClientConnectionId:a7da0ddb-bccf-490f-bc1e-ecd2eb4eab04
**There is already an object named 'UserProfile' in the database.**

我知道对象存在.我的意思是,我尝试使用自动迁移来精确地修改和运行,而无需手动重新创建数据库.但不知何故这不起作用.

I know the object exists. I mean, I'm try to use automatic-migrations to, precisely, modify and run without recreating manually the DB. But somehow this isn't working.

我查看了 MSDN 文档并找到了该属性:

I look the MSDN documentation and found the property:

AutomaticMigrationDataLossAllowed = true;

但是将其设置为 true 不会改变任何内容.我想我错过了一些东西,但不知何故没有找到什么.有什么想法吗?

But setting it to true doesn't change anything. I guess I'm missing something but somehow doesn't find what. Any idea?

推荐答案

update-database -verbose 不起作用,因为在您的数据表已经存在之后您的模型已更改.

update-database -verbose doesn't work because your model has been changed after your data table already existed.

首先,确保 UserProfile 类没有更改.然后,运行:

First, make sure there are no changes to the UserProfile class. Then, run:

Add-Migration InitialMigrations -IgnoreChanges

这应该会生成一个空白的InitialMigration"文件.现在,向 UserProfile 类添加任何所需的更改.添加更改后,再次运行更新命令:

This should generate a blank "InitialMigration" file. Now, add any desired changes to the UserProfile class. Once changes are added, run the update command again:

update-database -verbose

现在将应用自动迁移,表格将随着您的更改而改变.

Now the automatic migration will be applied and the table will be altered with your changes.

这篇关于ASP.NET SimpleMembershipProvider 的自动迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆