创建表并在EF代码首次迁移期间向其中插入数据 [英] Create table and insert data into it during EF code first migration

查看:127
本文介绍了创建表并在EF代码首次迁移期间向其中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework Code First和Code First迁移.

I'm using Entity Framework Code First with Code First migrations.

在迁移期间,我需要创建一个新表,然后将一些数据插入其中.

During a migration, I need to create a new table, and then insert some data into it.

所以我用:

CreateTable("MySchema.MyNewTable",
    c => new
    {
        MYCOLUMNID = c.Int(nullable: false, identity: true),
        MYCOLUMNNAME = c.String(),
     })
   .PrimaryKey(t => t.MYCOLUMNID);

然后我尝试使用:

using (var context = new MyContext())
{
    context.MyNewTableDbSet.AddOrUpdate(new[]
    {
    new MyNewTable
    {
       MYCOLUMNNAME = "Test"
    }
    });
    context.SaveChanges();
}

但是我得到一个错误:

无效的对象名称"mySchema.MyNewTable".

Invalid object name 'mySchema.MyNewTable'.

有可能做我需要做的事情吗?创建表并在同一迁移中向其中插入数据吗?

Is it possible to do what I need ? Create a table and inserto data into it in the same migration ?

我已经有其他迁移,可以在其中创建表或将数据插入到表中,但是从未在同一迁移中...

I already have other migrations where I create tables or insert data into a table, but never in the same migration...

推荐答案

我的建议是将插入代码移动到 DbMigrationsConfiguration 类.此Seed方法在两个重要方面与数据库初始化程序Seed方法不同:

My recommendation is move that insert code to the Seed method. Migrations introduced its own Seed method on the DbMigrationsConfiguration class. This Seed method is different from the database initializer Seed method in two important ways:

  • 只要执行Update-Database PowerShell命令,它就会运行. 除非使用迁移初始化程序,否则迁移Seed 应用程序启动时将不会执行该方法.
  • 它必须处理数据库已经包含数据的情况,因为 迁移是在发展数据库,而不是删除数据库和 重新创建它.
  • It runs whenever the Update-Database PowerShell command is executed. Unless the Migrations initializer is being used the Migrations Seed method will not be executed when your application starts.
  • It must handle cases where the database already contains data because Migrations is evolving the database rather than dropping and recreating it.

由于最后一个原因,在Seed方法中使用AddOrUpdate扩展方法很有用. AddOrUpdate可以检查数据库中是否存在实体,然后如果不存在则插入新实体,或者如果存在则更新现有实体.

For that last reason it is useful to use the AddOrUpdate extension method in the Seed method. AddOrUpdate can check whether or not an entity already exists in the database and then either insert a new entity if it doesn’t already exist or update the existing entity if it does exist.

因此,尝试以这种方式运行您想要的脚本:

So, try to run the script that you want this way:

 Update-Database –TargetMigration: ScriptName 

Seed方法将完成插入数据的工作.

And the Seed method will do the job of inserting data.

正如朱莉·勒曼(Julie Lerman)在她的博客上所说的那样:

As Julie Lerman said on her blog:

AddOrUpdate的工作是确保您不创建重复项 在开发过程中播种数据时.

The job of AddOrUpdate is to ensure that you don’t create duplicates when you seed data during development.

这篇关于创建表并在EF代码首次迁移期间向其中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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