Fix the Add Migrations "Build Failed" error for Entity Framework Core


This kind of error was faced by many newcomers to ASP.Net Core when it comes to Add the Migrations for the first time in their Project. First of all, make sure you've installed Entity Framework Core tools for .Net Core, then make sure your project contains the package Microsoft.EntityFrameworkCore.Design in references. If not then follow the steps below to install both the tools:

1. For EF Core 3.x

dotnet ef  tool must be installed as a local or global tool. Most developers install dotnet ef as a global tool with the following command:
dotnet tool install --global dotnet-ef
Run this command in Command Prompt or in PowerShell. Then use the below command for Adding Migrations to your Default Project:
dotnet-ef migrations add InitialCreate
If you can see in command that there's an '-' in-between dotnet and ef, well after you install Entity Framework tool for .Net Core, you'll see a result which says that you can invoke the tool using dotnet-ef command that's why it is there.

2. Install Microsoft.EntityFrameworkCore.Design

In the Package Manager Console, type:
dotnet add package Microsoft.EntityFrameworkCore.Design
Note: If your connection in appsettings.json is not defined in proper format then do the below steps.
First of all, if you have this kind of format in appsettings.json then,
"Data": {
"ConnectionStrings": {
  "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"},
}
If you would have noticed that in ASP.Net Webforms, we put our connection string in Connection String attribute; but in appsettings.json, we have to do in this format so, that your ApplicationDbContext file can properly get the connection string value from the key you've defined there,
"ConnectionStrings": {
  "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"},
Now the extension method will work. Underneath the Microsoft extensions, it is the same thing as the code below.
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

The Above steps were if you face the error System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString') while running dotnet-ef migrations add InitialCreate.

I hope this helps😊

Comments