-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbMigrations
57 lines (44 loc) · 2.3 KB
/
DbMigrations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
--- Entity Framework core Db migrations code first ---
Benifits of Code first
Database version control
Suitable for unstable database schema which keep on changing
No need to rewrite all sql queries if you are porting to another RDBMS
All queries written in linqtoSql so easy to adopt any RDBMS
How to create DbMigration solution
Create a Empty Web project
Install nuget packages
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Tools.DotNet
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer ( for sql server )
Microsoft.EntityFrameworkCore.SqlServer.Design ( for sql server )
--- Initial setups ---
Create DbContext class file
Set up Startup Class
Read connection string from appsettings
Register service AddDbContext in ConfigureServices block
--- Table creation ---
Create your entity in Models (POCO Class)
Entity Names as Table name, Properties as Table columns, Datatype will be converted into db types
Attributes used to set Column length Primary key and column properties
Add created entity in DbContext Onmodelcreating modelbuilder
Entities specified in Modelbuilder will be created in database tables
--- Migrations ---
Run CLI cmd :- dotnet ef migrations add <MigrationName>
This will create Migrations inside Migrations folder in the solution
DbContextModelSnapshot.cs file has all info about the database
Snapshot file maintains all migration history
Migration file for every migration a new migration file will be generated.
It maintain current changes. File name Timestamp_MigrationName (20170925112828_Migration_1.cs)
--- How migration works ---
While add migration cmd snapshot compare the model entities
It will track the changes eg: datatype changes, new column, new table
Changes will be added into new migration file
--- To Update Database ---
Run CLI cmd :- dotnet ef database update
On update database a new table created as __EFMigrationsHistory columns MigrationId, ProductVersion
Migration file name will be inserted into MigrationId column and Entity framework package version in ProductVersion column
--- How database update works ---
__EFMigrationsHistory table maintains the migration history
It will compare the Migration file list and __EFMigrationsHistory table
Update the database if migration file name not exist in the __EFMigrationsHistory table.