向身份模型添加了 属性 并迁移了数据库

Added property to Identity model and migrate the database

我有一个带有个人用户帐户身份验证的 MVC5 项目。我自己做了一个测试注册,一切正常。然后为了测试,我添加了一个 属性 到 ApplicationUser class,现在我看起来像这样:

public class ApplicationUser : IdentityUser
{
    public string NewPropery { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

然后我在 Visual Studio 2013 和 运行 中打开了包管理器控制台:

PM> Enable-Migrations
PM> Add-Migration "NewProperty"
PM> Update-Database

前两个命令运行良好,但在第三个命令上失败,这是错误:

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

数据库是常规的MVC模板创建的LocalDb,我在项目中保留了创建时的连接字符串:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-NyProject.Web-20160325120840.mdf;Initial Catalog=aspnet-MyProject.Web-20160325120840;Integrated Security=True"
      providerName="System.Data.SqlClient" />

哪里出错了?

更新 1 - 在史蒂夫发表评论后

我使用 select 程序包管理器控制台中的项目,使项目成为 "Startup project" 这将产生不同的错误 There is already an object named 'AspNetRoles' in the database.。 这是真实的。我应该删除预先存在的表吗?我的数据怎么办?

您收到该错误是因为您尚未建立基线初始迁移,因此 EF 认为您的所有对象都需要创建。这是因为它根据代码构建模型,并将其与上次迁移时存储的快照进行比较,所以试试这个:

1) Comment out the new field.
2) Delete the existing migration.
3) Add a baseline migration: add-migration Initial -IgnoreChanges
4) update-database (now EF has a snapshot to compare changes to).
5) add-migration NewProperty
6) update-database

EF Under the Hood