code-首先迁移过程:我缺少什么地方? [英] Code-First Migration Process: What part am I missing?

查看:180
本文介绍了code-首先迁移过程:我缺少什么地方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的步骤:

1)与查询创建我的SSMS中的数据库

1) Create my database in SSMS with the query

/* Execute in SQL Server Management Studio prior to building data model(s) */

CREATE DATABASE snakedb; 

GO

USE snakedb;

/*
   Create table of scores of games played. Every game will have a score recorded, but there
   will only be a corresponding name if the user enters one
*/
CREATE TABLE Scores ( id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
                      score int NOT NULL,
                      name VARCHAR (50) 
                    );

/* 
    Create table of text logs of the games played. These are reviewed to sniff out cheating.  
*/
CREATE TABLE GameLogs ( id int IDENTITY(1,1) NOT NULL PRIMARY KEY, 
                        scoreId INT NOT NULL FOREIGN KEY REFERENCES scores(id) ON DELETE CASCADE ON UPDATE CASCADE, 
                        logText VARCHAR (8000)
                       ); 

/*
    Table of unique IP addresses that have visited the site. The 4 decimal numbers separated by dots that compose each
    IP address, e.g. the 172, 16, 254 and 1 in 172.16.254.1, correspond to the 4 columns byte1, byte2, byte3 and byte4
*/
CREATE TABLE IPs ( id int IDENTITY (1,1) NOT NULL PRIMARY KEY, 
                   byte1 tinyint, 
                   byte2 tinyint, 
                   byte3 tinyint, 
                   byte4 tinyint 
                  );

/*
     Table of banned IP addresses 
*/
CREATE TABLE BannedIPs ( id int IDENTITY (1,1) NOT NULL PRIMARY KEY, 
                         ipId int NOT NULL FOREIGN KEY REFERENCES IPs(id)
                        );

2)右键单击文件夹迁移 - >添加新项 - 从数据库首先> code - - > ADO.NET实体数据模型>(浏览向导选择新创建 snakedb ,并创建相应的C#文件)

2) Right-click Migrations folder -> Add New Item -> ADO.NET Entity Data Model -> Code First from database -> (Go through the wizard to select the newly created snakedb and create the corresponding C# files)

3)现在我有我的文件夹迁移新文件 BannedIP.cs Configuration.cs GameLog.cs IP.cs Score.cs SnakeDB.cs

3) Now I have in my Migrations folder new files BannedIP.cs, Configuration.cs, GameLog.cs, IP.cs, Score.cs and SnakeDB.cs

4):要一个过程,根据这里的说明种子我的数据库,我改变我的 Configuration.cs

4) To a procedure to seed my database according to the instructions here, I change my Configuration.cs to

namespace SnakeGame.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using SnakeGame.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<SnakeGame.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        //protected override void Seed ( SnakeGame.Migrations.SnakeDB context)
        protected void Seed (SnakeGame.Migrations.SnakeDB context)
        {

            // Test data for seeding the database

            context.IPs.AddOrUpdate(
                i => i.id,
                new IP() { id = 1, byte1 = 4, byte2 = 35, byte3 = 241, byte4 = 179 },
                new IP() { id = 2, byte1 = 172, byte2 = 16, byte3 = 254, byte4 = 1 }
            );

            context.BannedIPs.AddOrUpdate(
                i => i.id,
                new BannedIP() { id = 1, ipId = 1}
            );

            context.Scores.AddOrUpdate(
                s => s.id,
                new Score() {  id = 1, score1 = 12, name = "John Skeet" },
                new Score() {  id = 2, score1 = 1923, name = "Steve Ballmer"}
            );
        }
    }
}

5) DROP 数据库 snakedb ,因为,据我所知,我将能够重新创建它,并在接下来的步骤中添加一些测试数据

5) I DROP the database snakedb because, as I understand, I will be able to recreate it and add some test data in the next step

6)我跑

Add-Migration Initial
Update-Database

在Package Manager控制台并得到输出

in the Package Manager console and get the output

Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201509300534414_Initial].
Applying explicit migration: 201509300534414_Initial.
Running Seed method.

但是当我返回到SSMS,没有数据库已创建。

but when I go back into SSMS, no database has been created.

有我丢失的东西?

此外,指示说

第一个命令生成code创建数据库,和
  第二个命令执行code。该数据库在本地创建,
  使用的LocalDB。

The first command generates code that creates the database, and the second command executes that code. The database is created locally, using LocalDB.

和我不知道这是否是我能够做到这一点与远程数据库以及。有没有什么办法让一个ASP.NET项目,这样的发布的,而不是在控制台运行的命令,种子数据库?

and I'm wondering whether this is possible for me to do this with a remote DB as well. Is there any way to make an ASP.NET project so that publishing, rather than running the commands in the console, seeds the database?

推荐答案

您数据库上下文的定义应该是这个样子:

Your database context definition should look something like this:

public class ApplicationDbContext: DbContext
{
    public ApplicationDbContext() : base("connectionString")
    {
    }

    public DbSet<Scores> Scores { get; set; }
    public DbSet<GameLogs> GameLogs { get; set; }
    public DbSet<IPs> IPs { get; set; }
    public DbSet<BannedIPs> BannedIPs { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

的DbContext 继承并定义你的对象模型的结构。

it inherits from DbContext and defines the structure of your object model.

DbSet(S)应该映射到你的类:


  • 得分

  • GameLogs

  • IP地址

  • BannedIPs

正如你所看到的构造函数需要一个连接字符串:

As you can see the constructor needs a connection string:

public ApplicationDbContext() : base("connectionString")
{
}

必须在定义

的web.config (或的app.config

<connectionStrings>
    <add name="connectionString" connectionString="Server=localhost;Database=MigrationsTest;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

&LT;结构&gt; 部分。我使用本地主机在这里,但是,当然,你可以用你的远程数据库。

inside <configuration> section. I've used localhost here but, of course, you can use your remote database.

现在从软件包管理器控制台您必须启用了迁移启用的迁移。结果
此命令将建立配置文件,应该是这个样子:

Now from Package Manager Console you must have enabled the migration with Enable-Migrations.
This command will build the configuration file which should look something like this:

internal sealed class Configuration : DbMigrationsConfiguration<MigratingDatabase.SchoolContext>
{
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(MigratingDatabase.SchoolContext context)
        {

        }
}

我可以在你的配置类看到它从数据库上下文继承:

what I can see in your Configuration class it inherits from the database context:

DbMigrationsConfiguration<SnakeGame.Models.ApplicationDbContext>

但它试图播种不同的对象:

but it is trying to seed a different object:

protected void Seed (SnakeGame.Migrations.SnakeDB context)
{

}

和,我想,应该是:

protected void Seed (SnakeGame.Models.ApplicationDbContext context)
{

}

当一切都在地方,你可以运行:

when everything is in place you can run:

Update-Database -Verbose

和它应该建立数据库给你。

and it should build the database for you.

你所要做的,以使迁移的另一件事是改变配置类的构造函数:

Another thing you have to do to enable the migration is change the constructor of the configuration class:

public Configuration()
{
    AutomaticMigrationsEnabled = true;
}

使用

AutomaticMigrationsEnabled = TRUE

这篇关于code-首先迁移过程:我缺少什么地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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