43

所以我試圖使用自動遷移與我的新MVC 4項目,但它不工作。我一步一步地走過去。自動遷移爲ASP.NET SimpleMembershipProvider

我添加(在NotaryCode場)更改到UserProfile賬戶模型:

[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上和配置類出現(從DbMigrationsConfiguration<Web.Models.UsersContext>繼承),那麼我填以班級爲:

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但這不起作用。我的意思是,這是輸出:

數據庫中已經有一個名爲'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.** 

我知道對象存在。我的意思是,我嘗試使用自動遷移來準確地修改和運行,而無需手動重新創建數據庫。但不知何故,這是行不通的。

我看MSDN文檔,發現物業:

AutomaticMigrationDataLossAllowed = true; 

但其設置爲true不會改變任何東西。我想我錯過了一些東西,但不知何故沒有找到。任何想法?

+0

請看看我的答案http://stackoverflow.com/questions/26305273/there-is-already-an-object-named-in-the-database/28316226#28316226 希望這會有所幫助... –

回答

127

update-database -verbose不起作用,因爲您的模型在您的數據表已經存在後已被更改。

首先,確保UserProfile類沒有變化。然後,運行:

Add-Migration InitialMigrations -IgnoreChanges

這應該產生一個空白 「InitialMigration」 文件。現在,向UserProfile類添加所需的更改。一旦改變被添加,再次運行更新命令:

update-database -verbose

現在的自動遷移將應用和表格將根據您的變化而改變。

+5

其實這個工作完美。不幸的是我不能給你超過+1和接受的答案。你節省了我很多頭痛。再次感謝。接下來的事情是,我應該總是使用Add-Migration InitialMigrations?或者這只是第一次。我沒有找到任何關於它的在線文檔。 –

+1

不客氣。 您只需要運行一次即可創建一個InitialMigrations類。 –

+3

同樣的問題。這個解決方案也適用於我。謝謝! +1 – kmehta

6

它看起來像在這裏發生的是,您啓用了遷移,然後運行該應用程序。通過在使用UpdateDatabase命令之前運行應用程序,EntityFramework將創建並填充數據庫,但自從啓用遷移時數據庫不存在時,它不會創建InitialCreate遷移。遷移仍然認爲你有一個空的數據庫,並且想要創建模型中的所有對象

你可以嘗試的是重新啓用遷移,它將生成反映數據庫當前狀態的InitialCreate遷移。在這種情況下,我將保存對seed方法所做的更改,而不是運行「Enable-Migrations -Force」,這應該重新創建遷移並生成IntialCreate遷移。然後,您可以重新填充種子方法並運行UpdateDatabase命令。

+0

我已經試過(2天前)和nop。它不起作用。 –

0

我有同樣的,並以不同的方式排序。去我的本地數據庫刪除UserProfile和其他表具有外鍵約束webpages_Membership,webpages_OAuthMembership,webpages_Roles,webpages_UsersInRoles表。所有這些將在您運行update-database -verbose時重新創建。