在 EF 代码首次迁移期间创建表并将数据插入其中

Create table and insert data into it during EF code first migration(在 EF 代码首次迁移期间创建表并将数据插入其中)
本文介绍了在 EF 代码首次迁移期间创建表并将数据插入其中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

So I create the table with :

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

Then I try to insert data with :

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

But I get an error :

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...

解决方案

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:

  • 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.

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 

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

As Julie Lerman said on her blog:

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)