代码优先迁移过程:我错过了哪个部分?

时间:2015-09-30 06:00:11

标签: c# asp.net asp.net-mvc entity-framework ef-code-first

我的步骤:

1)使用查询

在SSMS中创建我的数据库
/* 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)右键单击“迁移”文件夹 - >添加新项目 - > ADO.NET实体数据模型 - >数据库中的代码优先 - > (通过向导选择新创建的snakedb并创建相应的C#文件)

3)现在,我的迁移文件夹中有新文件BannedIP.csConfiguration.csGameLog.csIP.csScore.csSnakeDB.cs

4)要根据此处的说明为我的数据库播种一个过程,我将Configuration.cs更改为

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,因为据我所知,我将能够重新创建它并在下一步添加一些测试数据

6)我跑

Add-Migration Initial
Update-Database
在程序包管理器控制台中

获取输出

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时,没有创建任何数据库。

有什么我想念的吗?

另外,说明说

  

第一个命令生成用于创建数据库的代码,以及   第二个命令执行该代码。数据库是在本地创建的,   使用LocalDB。

我想知道我是否可以使用远程数据库执行此操作。有没有办法制作一个ASP.NET项目,以便发布,而不是在控制台中运行命令,为数据库播种?

1 个答案:

答案 0 :(得分:0)

您的数据库上下文定义应如下所示:

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并定义对象模型的结构。

您的DbSet(s)应该映射到您的班级:

  • 得分
  • GameLogs
  • IPs
  • BannedIPs

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

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>

<configuration>部分内。我在这里使用了localhost但是,当然,您可以使用远程数据库。

现在从Package Manager Console开始,您必须使用Enable-Migrations启用迁移 此命令将构建配置文件,该文件应如下所示:

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

        protected override void Seed(MigratingDatabase.SchoolContext context)
        {

        }
}

我在您从数据库上下文继承的Configuration类中可以看到的内容:

DbMigrationsConfiguration<SnakeGame.Models.ApplicationDbContext>

但它试图播种另一个对象:

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

}

而且,我想,它应该是:

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

}

当一切都到位后,您可以运行:

Update-Database -Verbose

它应该为你构建数据库。

启用迁移所需要做的另一件事是更改配置类的构造函数:

public Configuration()
{
    AutomaticMigrationsEnabled = true;
}

使用AutomaticMigrationsEnabled = true