代码首先创建表

Yus*_*tme 4 c# asp.net-mvc-4 ef-migrations entity-framework-5

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

 public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<TestTabel> 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; }
}
Run Code Online (Sandbox Code Playgroud)

比我尝试使用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>
Run Code Online (Sandbox Code Playgroud)

[/编辑]

Configuration.cs:

    namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Migrations
{
    internal sealed class Configuration : DbMigrationsConfiguration<UsersContext>
    {
        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" });
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在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<UsersContext>(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);
            }
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

连接字符串:

<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
Run Code Online (Sandbox Code Playgroud)

上次迁移:

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");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

NSG*_*aga 17

我只是将所有内容都放在这里作为一个步骤来实现代码优先和迁移 - 攻击可能会或可能不会发生的各种问题.注意:代码优先已被证明非常可靠 - 并且可以在实时场景中解决 - 您只需要知道自己在做什么.

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

您现有的迁移尝试针对数据库的旧副本运行 - 我猜测,这是针对'空数据库'优化的上/下.

您需要针对您所附加的Db副本运行迁移(添加迁移) - 这将创建一个"差异"并且只是更新您的Db(当然,总是确保备份,因为它可能会掉落/改变等).

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

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

您还可以查看我之前关于同步的帖子......

MVC3和Code First Migrations - "创建数据库后,支持'blah'上下文的模型已经改变"

编辑:
还检查此答案AutomaticMigrationsEnabled false或true?

如果你的做事方式还可以添加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'(调用您的数据项目/程序集 - 或控制台/应用程序中的相同项目) - 设置为'启动'项目,
- 始终观看控制台评论 - 因为它可能正在尝试构建和访问不同的项目.

连接:

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

构建:
确保您的项目设置为"配置"以自动构建 - 这也可能是一个问题.