代码首先创建表

我正在学习本教程,并尝试在userprofile表中添加一些新列。 我试图创建一个新表。

public class UsersContext : DbContext { public UsersContext() : base("DefaultConnection") { } public DbSet UserProfiles { get; set; } public DbSet TestTabel { get; set; } } [Table("UserProfile")] public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } public string Mobile { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } [Table("TestTabel")] public class TestTabel { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int TestId { get; set; } public string TestName { get; set; } public string TestMobile { get; set; } } 

比我尝试使用update-database命令用控制台更新数据库,我收到此错误信息:

数据库中已经有一个名为“UserProfile”的对象。

没有添加的新列,也没有表。

我错过了什么?

[编辑]我做了add-migration和update-database命令,这是出来的(必须两次执行update-database命令,第二次使用详细信息)

 PM> Add-Migration cmdlet Add-Migration at command pipeline position 1 Supply values for the following parameters: Name: test Scaffolding migration 'test'. The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration 201304011714212_test' again. PM> Update-Database The project 'MVC4SimpleMembershipCodeFirstSeedingEF5' failed to build. PM> Update-Database Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Applying code-based migrations: [201304011714212_test]. Applying code-based migration: 201304011714212_test. Running Seed method. PM> Update-Database -verbose Using StartUp project 'MVC4SimpleMembershipCodeFirstSeedingEF5'. Using NuGet project 'MVC4SimpleMembershipCodeFirstSeedingEF5'. Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Target database is: 'aspnet-MVC4SimpleMembershipCodeFirstSeedingEF5' (DataSource: ., Provider: System.Data.SqlClient, Origin: Configuration). No pending code-based migrations. Running Seed method. PM> 

[/编辑]

Configuration.cs:

  namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Migrations { internal sealed class Configuration : DbMigrationsConfiguration { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(UsersContext context) { WebSecurity.InitializeDatabaseConnection( "DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); if (!Roles.RoleExists("Administrator")) Roles.CreateRole("Administrator"); if (!WebSecurity.UserExists("test")) WebSecurity.CreateUserAndAccount( "test", "password", new { Mobile = "+19725000374", FirstName = "test", LastName = "test" }); if (!Roles.GetRolesForUser("test").Contains("Administrator")) Roles.AddUsersToRoles(new[] { "test" }, new[] { "Administrator" }); } } } 

在Filters文件夹1 cs文件中:

 namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute { private static SimpleMembershipInitializer _initializer; private static object _initializerLock = new object(); private static bool _isInitialized; public override void OnActionExecuting(ActionExecutingContext filterContext) { // Ensure ASP.NET Simple Membership is initialized only once per app start LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); } private class SimpleMembershipInitializer { public SimpleMembershipInitializer() { Database.SetInitializer(null); try { using (var context = new UsersContext()) { if (!context.Database.Exists()) { // Create the SimpleMembership database without Entity Framework migration schema ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); } catch (Exception ex) { throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex); } } } } } 

连接字符串:

  

上次迁移:

 namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Migrations { using System; using System.Data.Entity.Migrations; public partial class test : DbMigration { public override void Up() { CreateTable( "dbo.TestTabel", c => new { TestId = c.Int(nullable: false, identity: true), TestName = c.String(), TestMobile = c.String(), }) .PrimaryKey(t => t.TestId); } public override void Down() { DropTable("dbo.TestTabel"); } } } 

我只是想把所有内容都放在这里,作为让你的代码优先和迁移进行的一个步骤 – 攻击可能会或可能不会发生的各种问题。 注意:代码优先已被certificate非常可靠 – 并且可以通过实时场景解决 – 您只需要知道自己在做什么。

最有可能的是,您的迁移和数据库基本上不同步。

您现有的迁移尝试针对数据库的旧副本运行 – 我猜测是针对’空数据库’优化的上/下。

您需要针对您附加的Db副本运行迁移(添加迁移) – 这将创建“差异”并且只更新您的Db(当然,请务必备份 ,因为它可能会掉落/改变等)。

或者如果可能的话,清空您的Db – 然后重新开始。

或者,如果直播Db – 创建迁移 – 并在您的开发机器上运行Update-Database -Script – 生成完整的Db – 或更改(这非常粗糙,您需要根据您的情况进行调整)。 然后通过运行脚本应用于您的’live Db’。

您还可以查看我之前关于同步的post……

MVC3和Code First Migrations – “创建数据库后,支持’blah’上下文的模型已经改变”

编辑:
还要检查此答案AutomaticMigrationsEnabled是假还是真?

如果你的做事方式没问题,可以添加AutomaticMigrationsEnabled = true; 给你Configuration (也在Migrations文件夹下 – 为你创建)..

我总是采取一些步骤来清理迁移:

(先备份好)
– Enable-Migrations -force(仅限第一次 – 这会删除configuration.cs以及任何’种子’!)
– AutomaticMigrationsEnabled = true;
– 从项目中手动删除现有迁移(\ Migrations)
– 此时重建项目
– Add-Migration Initial
– Update-Database -Force -Verbose

……稍后(后续迁移):
– Add-Migration SomeOther1
– Update-Database -Force -Verbose
…让你保持你的Db同步 – 即小心’移动Db’,手动调整等等(在这种情况下看另一篇文章)

结合其他事情:

使用PM控制台……
– 从列表中选择您的项目,
– 确保你的’main exe’(调用你的数据项目/程序集 – 或控制台/应用程序的同一个项目) – 被设置为’startup’项目,
– 始终观看控制台评论 – 因为它可能正在尝试构建和访问不同的项目。

连接:

看到我的这篇文章, 迁移不会改变我的表格
简而言之 – 您的连接被命名为您的上下文+您的项目 – 如果没有另外指定。 它来自您的DbConfig构造函数 – 或app.config(连接)。 确保您正在查看“正确的数据库”(即您通过某个资源管理器查看的内容以及代码优先连接到的内容 – 可能是两个不同的东西)。

建造:
确保您的项目设置为“配置”以自动构建 – 这也可能是一个问题。