Alice52 / c-tutorial

The repository is about c, including c, csharp, cpp.
MIT License
0 stars 0 forks source link

[migration] code first #5

Open Alice52 opened 4 years ago

Alice52 commented 4 years ago

Usage of Migrations

  1. create sql in DataBase, and use follow command to generate code

    dotnet ef dbcontext scaffold "Server=T0xx-111\SQLEXPRESS;Database=DATABASE_NAME;User Id=sa; Password=sa" Microsoft.EntityFrameworkCore.SqlServer -f -t TABLE_NAME1 -t TABLE_NAME2 --output-dir Models --context-dir Db --context CustomContext --verbose
  2. copy and refine code

    • Model: entity model
    • Configuration: entity create code
    • CustomDbContext: add Models and point out datasource in OnConfiguring
  3. add follow code to point out datasource in xxDbContext

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=192.168.111.xxx;Database=DATABASE_Name;User Id=sa; Password=sa");
    }
  4. open TableManagement.DataAccess project and run the follow command to generate Migrations and DB

    dotnet ef migrations add MIGRATION_NAME
    dotnet ef database update 
    # this will generate sql
    dotnet ef migrations script -o Custom_Directory 

explain

  1. when we execute migration add command, it will do the follow jobs

    • compare source code to xxSnapshot and generate incremental changes
  2. when we execute database update command, it will do the follow jobs

    • get all local incremental changes
    • read data from __EFMigrationsHistory
    • then will execute incremental change one by one if which donot in database table
    • and if __EFMigrationsHistory data is more than local, it will ignore this record

reference

  1. https://www.jianshu.com/p/42bbbfa2993f