2.1: Add Migration and Database
Referencing Entity Framework Core CLI Tool
Now we will add a package to allow us to use Entity Framework Core and run migrations with the CLI.
In your terminal - navigate to EFConnect.Data
and run the following commands to update the EFConnect.Data.csproj
file:
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools.DotNet
Ensure your updated EFConnect.Data.csproj
file roughly matches the following (versions of packages may be different:
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
</ItemGroup>
Restore your packages:
dotnet restore
Note: you may get strange error messages about a downgraded version:
error NU1605: EFConnect.Data -> Microsoft.EntityFrameworkCore.Tools.DotNet 2.0.2 -> Microsoft.NETCore.App (>= 2.0.6
If that's the case, specify the RuntimeFrameworkVersion
to match the error (in this case 2.0.6:
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.6</RuntimeFrameworkVersion>
</PropertyGroup>
Verify that the Entity Framework Core CLI tools were installed correctly:
dotnet ef
You should get a unicorn some some help information. Feel free to explore that.
_/\__
---==/ \\
___ ___ |. \|\
| __|| __| | ) \\\
| _| | _| \_/ | //|\\
|___||_| / \\\/\\
Entity Framework Core .NET Command Line Tools 2.0.1-rtm-125
Usage: dotnet ef [options] [command]
Options:
--version Show version information
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
Commands:
database Commands to manage the database.
dbcontext Commands to manage DbContext types.
migrations Commands to manage migrations.
Running Our First Migration
Let's run our first migration.
In your EFConnect.Data
folder, run the following command:
dotnet ef migrations add InitialCreate -s "../EFConnect.API/EFConnect.API.csproj"
We added an option (-s
) to tell Entity Framework Core the location of our Startup
project - since our .Data
project is separate from our .API
project.
This blog post provided a solution to the above problem. Read it if you would like to understand in-depth.
Creating Our Database
To create our database (or to update the database with a migration in the future) we'll run this command:
dotnet ef database update -s "../EFConnect.API/EFConnect.API.csproj"
We won't run it now, but it's good to have this command in your back pocket incase you run into issues.
This removes the latest migration:
dotnet ef migrations remove -s "../EFConnect.API/EFConnect.API.csproj"
Last updated