code首先创建表 [英] Code first create tables

查看:344
本文介绍了code首先创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面<一个href=\"http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-$c$cfirst-and-custom-user-properties\"相对=nofollow>本教程,我试着在USERPROFILE表中添加了一些新的栏目。我试图创建新表。

 公共类UsersContext:的DbContext
{
    公共UsersContext()
        :基地(DefaultConnection)
    {
    }    公共DbSet&LT;用户配置&GT; {的UserProfiles获得;组; }
    公共DbSet&LT; TestTabel&GT; TestTabel {搞定;组; }
}[表(用户配置)]
公共类用户配置
{
    [键]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)
    公众诠释用户ID {搞定;组; }
    公共字符串用户名{获得;组; }
    公共字符串移动{搞定;组; }
    公共字符串名字{获得;组; }
    公共字符串名字{获得;组; }
}[表(TestTabel)]
公共类TestTabel
{
    [键]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)
    公众诠释TestId {搞定;组; }
    公共字符串测试名{获得;组; }
    公共字符串TestMobile {搞定;组; }
}

比我尝试更新与更新数据库命令控制台的数据库,我得到这个错误信息:

已经有一个数据库名为用户配置的对象。

在这里没有添加,而新列既不表。

我是什么失踪?


我做了附加迁移和更新数据库命令,这是出落得(不得不做更新数据库命令两次,第二次与详细)

  PM&GT;添加迁移
cmdlet的附加迁移在命令管道位置1
以下参数提供值:
名称:测试
脚手架迁移测试。
该设计师code这个迁移文件包括您目前的code首先模型的快照。该快照用于计算更改模型,当你脚手架下一个迁移。如果你要在此迁移包括到模型的其他变化,那么你可以通过再次运行添加 - 迁移201304011714212_test重新脚手架它。
PM&GT;更新 - 数据库
该项目的MVC4SimpleMembership codeFirstSeedingEF5未能建立。
PM&GT;更新 - 数据库
指定'-Verbose'标志,以查看被施加到目标数据库的SQL语句。
应用code为基础的迁移:[201304011714212_test]。
应用code为基础的迁移:201304011714212_test。
运行种子法。
PM&GT;更新,数据库-verbose
使用启动项目的MVC4SimpleMembership codeFirstSeedingEF5。
使用的NuGet项目的MVC4SimpleMembership codeFirstSeedingEF5。
指定'-Verbose'标志,以查看被施加到目标数据库的SQL语句。
目标数据库是:'ASPNET-MVC4SimpleMembership codeFirstSeedingEF5'(数据源:,提供者:System.Data.SqlClient的,产地:配置)。
无待code为基础的迁移。
运行种子法。
PM&GT;

[/编辑]

Configuration.cs:

 命名空间MVC4SimpleMembership codeFirstSeedingEF5.Migrations
{
    内部密封类配置:DbMigrationsConfiguration&LT; UsersContext&GT;
    {
        公共配置()
        {
            AutomaticMigrationsEnabled = TRUE;
        }    保护覆盖无效的种子(UsersContext上下文)
    {
        WebSecurity.InitializeDatabaseConnection(
            DefaultConnection
            用户资料,
            用户名,
            用户名,autoCreateTables:真正的);        如果(!Roles.RoleExists(管理员))
            Roles.CreateRole(管理员);        如果(!WebSecurity.UserExists(测试))
            WebSecurity.CreateUserAndAccount(
                测试,
                密码,
                新{移动=19725000374,名字=测试,姓氏=测试});        如果(!Roles.GetRolesForUser(测试)。包含(管理员))
            Roles.AddUsersToRoles(新[] {测试},新的[] {管理员});
    }
  }
}

在过滤器文件夹1 CS文件:

 命名空间MVC4SimpleMembership codeFirstSeedingEF5.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,的AllowMultiple =假,    继承= TRUE)]
    公共密封类InitializeSimpleMembershipAttribute:ActionFilterAttribute
    {
        私有静态SimpleMembershipInitializer _initializer;
        私人静态对象_initializerLock =新的对象();
        私人静态布尔_isInitialized;        公共覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
        {
            //确保ASP.NET简单成员初始化每个应用程序启动只有一次
            LazyInitializer.EnsureInitialized(REF _initializer,裁判_isInitialized,裁判_initializerLock);
        }
    私有类SimpleMembershipInitializer
    {
        公共SimpleMembershipInitializer()
        {
            Database.SetInitializer&LT; UsersContext&GT;(NULL);            尝试
            {
                使用(VAR上下文=新UsersContext())
                {
                    如果(!context.Database.Exists())
                    {
                        //创建无实体框架迁移架构SimpleMembership数据库
                        )((IObjectContextAdapter)上下文).ObjectContext.CreateDatabase(;
                    }
                }                WebSecurity.InitializeDatabaseConnection(DefaultConnection,用户配置,用户ID,用户名,autoCreateTables:真正的);
            }
            赶上(异常前)
            {
                抛出新的InvalidOperationException异常(以下简称ASP.NET简单的会员数据库无法初始化欲了解更多信息,请参阅http://go.microsoft.com/fwlink/?LinkId=256588。恩);
            }
        }
    }
  }
}

连接字符串:

 &LT; configSections&GT;
&lt;节名称=的EntityFrameworkTYPE =System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本5.0.0.0 =文化=中性公钥= b77a5c561934e089requirePermission =FALSE/&GT;
&LT; / configSections&GT;

最后迁移:

 命名空间MVC4SimpleMembership codeFirstSeedingEF5.Migrations
{
    使用系统;
    使用System.Data.Entity.Migrations;公共部分类测试:DbMigration
{
    公共覆盖无效向上()
    {
        CREATETABLE(
            dbo.TestTabel
            C =&GT;新
                {
                    TestId = c.Int(可空:假的,身份:真)
                    测试名= c.String()
                    TestMobile = c.String(),
                })
            .PrimaryKey(T =&GT; t.TestId);    }    公共覆盖无效向下()
    {
        DROPTABLE(dbo.TestTabel);
    }
  }
}


解决方案

我只是在这里抛开一切作为步行通过让你的code-第一和迁移会 - 攻击,可能会或可能不会发生各种问题。注:code-先已被证明是非常可靠的 - 并能与活的情况制定出以及 - 你只需要知道你在做什么


  

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


您现有的移民试图对数据库的旧副本运行 - 与UPS /这是为'空分贝我想优化的起伏。

您需要运行迁移(附加迁移)对,你连接到数据库的拷贝 - 这将创建一个差异和刚上来最新您的数据库(总是使一定要备份当然,因为它可能会跌落/等变化)。

或者,如果可能的话,清空你的数据库 - 然后重新开始。

或者,如果现场分贝 - 创建迁移 - 并运行更新,数据库-Script 您的开发机上 - 以生成完整分贝 - 或改变(这是所有非常粗糙,您需要调整您的情况)。然后通过运行脚本适用于您的实况分贝。

您还可以检查我先前的职位上的同步...

<一个href=\"http://stackoverflow.com/questions/10254613/mvc3-and-$c$c-first-migrations/10255051#10255051\">MVC3和code首先迁移

编辑:结果
还要检查这个答案<一个href=\"http://stackoverflow.com/questions/11806570/automaticmigrationsenabled-false-or-true/11815229#11815229\">AutomaticMigrationsEnabled或真或假?

和它是否可以与你的做事添加方式 AutomaticMigrationsEnabled = TRUE; 配置(也下迁移的文件夹 - 为您创建)。


  

夫妇的步骤,我总是做清洁迁移:


(好先备份)结果
  - 启用 - 迁移-force(第一次只 - 这将删除configuration.cs任何'seed'-ING那里!)结果
- AutomaticMigrationsEnabled = TRUE;结果
- 移除现有的项目,从手工迁移(\\迁移)结果
- 在这一点结果重建项目
- 添加迁移初步结果
- 更新 - 数据库-Force -Verbose

...以后(后续迁移):结果
- 添加迁移SomeOther1结果
- 更新 - 数据库-Force -Verbose结果
...提供你保持你的数据库同步 - 即小心'走动分贝,手动调节等(在这种情况下,看到其他职位)

情侣其他的东西:

使用PM控制台...结果
- 从列表中选择你的项目,结果
- 确保你的主要exe文件(调用数据的项目/组件 - 或者说同一个项目中,如果主机/应用) - 设置为启动项目,结果
- 始终看控制台意见 - 因为它可能试图建立和访问不同的项目。

连接方式:

看到这个职位矿迁移不会改变我的表结果
总之 - 您的连接被命名为喜欢你的环境+你的项目 - 如果不是另有规定。它吸引了来自您的DBCONFIG构造 - 或app.config中(连接)。请确保你在寻找正确的数据库'(即你通过一些探险家,什么code-第一次连接到是什么 - 可能是两个不同的东西)。

楼:结果
确保您的项目在配置设置为自动构建 - 这可能是一个问题太

I was following this tutorial, and I tried to add a few new columns in the userprofile table. And i tried to create a new table.

 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; }
}

Than i tried to update the database with the console with the update-database command, and i got this error msg:

There is already an object named 'UserProfile' in the database.

The new columns where not added, and neither the table.

What am I missing?

[EDIT] I did the add-migration and update-database commands, and this is the out come (had to do the update-database command twice, 2nd time with verbose)

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>

[/EDIT]

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" });
    }
  }
}

In the Filters folder 1 cs file:

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);
            }
        }
    }
  }
}

Connection string:

<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>

Last migration:

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");
    }
  }
}

解决方案

I'm just going to throw everything in here as a walk-through for getting your code-first and migrations going - attacking various issues that may or may not happen. Note: code-first has proved to be very reliable - and can be worked out with live-scenarios as well - you just need to know what you're doing.

Most likely, your migration and the database are basically out-of-sync.

Your existing migration tries to run against the old copy of the database - with ups/downs that were optimized for the 'empty db' I guess.

You need to run your migrations (Add-Migration) against the copy of the Db that you're attaching to - that'll create a 'difference' and just up-to-date your Db (always make sure to backup of course, as it might drop/change etc.).

Or if possible, empty your Db - and then start fresh.

Or if live Db - create migrations - and run Update-Database -Script on your dev-machine - to generate the full Db - or the changes (this is all very rough, you need to adjust to your case). And then apply to your 'live Db' by running scripts.

You can also check my earlier post on the synchronization...

MVC3 and Code First Migrations

EDIT:
Also check this answer AutomaticMigrationsEnabled false or true?

And if it's ok with your way of doing things add the AutomaticMigrationsEnabled = true; to you Configuration (also under the Migrations folder - created for you)..

Couple steps I always do to clean migrations:

(good to backup first)
- Enable-Migrations -force (first-time only - this deletes the configuration.cs and any 'seed'-ing there!)
- AutomaticMigrationsEnabled = true;
- remove existing migrations by hand from project (\Migrations)
- rebuild the project at this point
- Add-Migration Initial
- Update-Database -Force -Verbose

...later on (subsequent migrations):
- Add-Migration SomeOther1
- Update-Database -Force -Verbose
...providing you keep your Db in sync - i.e. careful with 'moving Db around', manually adjusting etc. (and in that case see the other post)

Couple other things:

With PM Console...
- select your project from the list,
- make sure your 'main exe' (calling your data project / assembly - or that same project if console/app) - is set as 'startup' project,
- always watch the console comments - as it may be trying to build and access different project.

Connection:

See this post of mine Migration does not alter my table
In short - your connection is named like your context + your project - if not specified otherwise. It draws from your DbConfig constructor - or app.config (connections). Make sure you're looking at the 'right database' (i.e. what you look through some explorer and what code-first connects to - may be two different things).

Building:
Make sure your project is set in 'configuration' to build automatically - that can be an issue too.

这篇关于code首先创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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