ef核心迁移插入数据 [英] ef core migration insert data

查看:87
本文介绍了ef核心迁移插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在迁移过程中将数据插入表中。可能吗?迁移需要无参数的构造函数,我想使用Startup.cs文件中定义的db上下文(最好通过依赖注入来获取它)。

I'd like to insert data into table in migration. Is it possible? Migration needs parameterless constructor available and I'd like to use db context defined in Startup.cs file (best I'd like to get it throught dependency injection). How do that?

推荐答案

在EF Core 2.1中,迁移可以自动计算插入,更新或删除的内容

In the EF Core 2.1, migrations can automatically compute what insert, update or delete

操作。

例如,我们有一个User和一个这样的UserComment实体:

As an example, we have a User and UserComment entities like these:

public class User
  {
      public int UserId { get; set; }
      public string Name { get; set; }
      public List<UserComment> UserComments { get; set; }
  }

public class UserComment
  {
      [Key]
      public int CommentId { get; set; }
      public string CommentTitle { get; set; }
      [ForeignKey("User")]
      public int FKUserId { get; set; }
      public User User { get; set; }
  }

在DBContext中,重写OnModelCreating函数并将数据种子化到每个实体:

In the DBContext, override the OnModelCreating function and seed data to each entity:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().HasData(new User[] {
                new User{UserId=1,Name="iman"},
                new User{UserId=2,Name="Alex"},
            });
        }

要播种具有关系的数据,必须指定外键值:

To seed datas that have a relationship, the foreign key value must be specified:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
             modelBuilder.Entity<UserComment>().HasData(new UserComment[] {
                 new UserComment{FKUserId=1,CommentId=1,CommentTitle="Comment1"},
             });
        }

请注意:您必须使用迁移才能申请变化

Be careful: you must use migrations to apply changes

这篇关于ef核心迁移插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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