2020-02-12 09:00:58
Open Package Manager Console
Select Visual Studio menu item Tools | NuGet Package Manager | Package Manager Console
.
Connection String
Add a connection string to the assembly used to manage database interactivity. This will be the
This is done by appending the following to the root node of
<connectionStrings> <add name="SampleDbContext " connectionString="data source=.\LOCALDB; initial catalog=Sample; integrated security=SSPI" providerName="System.Data.SqlClient" /> </connectionStrings>
If the name provided is the same as the DbContext. In this example SampleDbContext
no additional steps are required, but if the names differ then a constructor must be created for the DbContext:
public class PlutoContext : BbContext { public PlutoContext() : base("name=SampleDbContext ") }
Enable migrations
Using the following command:
PM>enable-migrations
Got Ah!
No context type was found in the assembly '...'.
If this error is returned then change the <connectionString>
value in its App.config
. This is achieved by using a dropdown in the Package Manager Console.
A new folder titled Migrations
will be created in the Solution.
Add a Migration
PM>add-migration InitialModel
Choose a name that is suitable to the changes made to the POCO code.
Inside Migrations
you will see a new C# class. Its name is prefixed with an ISO date.
202002120900580_InitialModel.cs
Update the Database Schema
Once we have some migrations we can run the following:
PM>Update-Database
Overwrite a Migration
PM>add-migration InitialModel -force
For Example:
PM>add-migration AddIsSubscribedToCustomer
ASP.NET Identity Tables
If you have ASP.NET Identity as part of your project you will find that the migration class contains code to create these tables. The tables are:
-
dbo.AspNetRoles
-
dbo.AspNetUserRoles
-
dbo.AspNetUsers
-
dbo.AspNetUserLogins
-
dbo.AspNetUserClaims
These tables are added to the database along with a _MigrationHistory
Table. This table keeps track of migrations.