Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ef core migration insert data

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?

like image 922
Marek Avatar asked Dec 07 '17 05:12

Marek


2 Answers

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

operations must be applied when upgrading the database to a new version of the model.

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; }
  }

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

like image 76
Iman Bahrampour Avatar answered Oct 15 '22 02:10

Iman Bahrampour


Migration is a process of "upgrading" your DB to a new "version". During this, your existing DB tables ("old version") does not required to match your classes (entities) ("new version"), so you can't safely use them.

During migration you should operate only with tables and records using raw SQL commands. You may use migrationBuilder.Sql("UPDATE ..."); for such updates, put them manually into migration Up() code.

If you need perform data modifications using entity classes - you should use "Seed Data" solution (from @itikhomi comment), but remember that it will be run every time your app starts, so you should do some version-check inside it.

like image 28
Dmitry Avatar answered Oct 15 '22 02:10

Dmitry