ef core migration command is used to generate a database and tables

This article is about to Entity Framework Core had just learned to do a record, mainly to generate database and table with the command ef core of migration.

1. Create a new the .NET Core Console program

Here Insert Picture Description

2. Add the mysql dependent on project

This case using the mysql database, open Nuget Package Manager, install Pomelo.EntityFrameworkCore.MySql
Here Insert Picture Description

3. New Entity Classes

code show as below:

public class City
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public string AreaCode { get; set; }

        public int ProviceId { get; set; }

        public Provice Provice { get; set; }
    }
 public class Provice
    {
        public Provice()
        {
            Cities = new List<City>();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        public int Populatios { get; set; }
        public List<City> Cities { get; set; }
    }

4. Create a database context

  public class MyContent :DbContext
    {
        public DbSet<Provice> Provices { get; set; }

        public DbSet<City> Cities { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySql("server=127.0.0.1;userid=root;database=efcoredemo;sslmode=none;charset=utf8");
            
        }
    }

5. Open the Package Manager Console

Enter the get-help entityframeworkcore command, enter, will see ef core orders, here will be used Add-Migration, is to add a new migration, Remove-Migration removal of the last migration, Update-Database update database, Script-Migration sql statement is generated
Here Insert Picture Description

7. Add the migration

In the Package Manager console input Add-Migration Initial (a parameter required, its own custom migration name), adding the success of Migrations will generate a file, there will be migration of files
Here Insert Picture Description

8. Update the database

Then continue to input
an input Update-Database can complete execution in corresponding mysql entity classes and generating the table

9. Source demo

Published 14 original articles · won praise 6 · views 6335

Guess you like

Origin blog.csdn.net/weixin_43817709/article/details/90236511