Related
I face the following error when adding the migration of database in .net core
This is the error:
This is the code in Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllers();
}
This is the ApplicationDbContext class:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
public DbSet<ApplicationUser> applicationUsers { get; set; }
}
This is the ApplicationUser:
public class ApplicationUser : IdentityUser
{
[Required]
[Column(TypeName = "nvarchar(150)")]
public string UserFName { get; set; }
[Required]
public string UserLName { get; set; }
}
I found the cause of this error could be multiple things in your code. For me at least, the best way was to add verbose in command.
With that will be able to understand what is the problem. the verbose will display all steps of the execution.
In visual studio use:
add-migration Added_something -verbose
For the CLI use:
dotnet ef migrations add Added_something --verbose
This error can also occur if multiple startup projects is selected. I set my webproject to startup project and that solved the issue for me.
My problem was solved by installing Microsoft.EntityFrameworkCore.Design nuget package.
this package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct.then install the package.
at the end Build -> Clean Solution in your project and then try running your command again.
Help Link
add migration command cli:
dotnet ef migrations add InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
update database command cli:
dotnet ef database update InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
remove migration command cli:
dotnet ef migrations remove --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
Entity Framework Core tools reference - .NET Core CLI
I also had same problem today when I was running the dotnet ef migrations add <MigrationName>
I had three project, MainApp (Web), C# Project with DBContext and C# Project for Models.
I was able to resolve it from CLI.
dotnet ef migrations add AddCategoryTableToDb -s MainApp -p ProjectHavingDbContext
I had the same error when I had two constructors of my DbContext. After rearranging constructors order to parameterless constructor being first in the class fixed it. e.g.
public ProgramDbContext() : base()
{
}
public ProgramDbContext(DbContextOptions<ProgramDbContext> options) : base(options)
{
}
It must be something with dynamic DbContext object invocation with Reflection playing here.
This error also can occur if you remove the static IHostBuilder CreateHostBuilder(string[] args) method from Program.cs for your .net core app. (This was my case)
Seems you are your inheritance is wrong.
public ApplicationDbContext : IdentityDbContext
should be
public ApplicationDbContext : IdentityDbContext<ApplicationUser>
or
public ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole>
if you also extend roles class.
when you want to create an context with an extended user class (instead of IdentityUser)
Try This one as of March 2021 - VS 16.9.2
I tried many of the above answers and none worked for me. My issue was that we had multiple startup projects, so that was step one. Just set a single startup project, so I set our Data project to be the startup. Still got the error. Then it hit me (thanks to the #AFetter's answer) the Data project does NOT have a connection string within it. So I set my startup project to one with an appSettings.json file that HAS a connection to the DB and then made sure the Package Manager Console's Default Project was set to the Data project and reran the command to create the migration and it worked!
If you come to this issue while using .Net 6 along with the new minimal hosting model, check that you're not calling builder.build() before calling the AddDbContext on builder.services.
using MyProject.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
string relativePath = ".";
string databasePath = Path.Combine(relativePath, "MyDb.sqlite");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite($"Data Source={databasePath}") //connection string
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
I found I was missing:
Microsoft.EntityFrameworkCore.Tool
Microsoft.EntityFrameworkCore.Design
I had multiple startup projects (different API's).
I was at a different level in the PM console.
Then I learned I had to close SQL management so I can run PM console commands.
I was facing the same issue while running the dot net ef migrations script command from the azure pipeline task. I did added "-project" argument. But still was failing.
Adding the "-startup-project" argument worked for me.
I guess even though we specify startup class in project , for ef tool to find one we have to explicitly mention them.
In my case, I was missing a property in appsettings.json that was showing as Warning instead of Error
This error message is sometimes not directly related to the db context model. Check other errors in your Startup class such as missing properties/ credentials in your appsettings.json/ appsettings.Development.json
run your migration with the --verbose option to see all errors and warnings
dotnet ef migrations add YourMigrationName --verbose
If you are using Docker-Compose project. You need to unload the Docker-Compose project and then clean and rebuild the solution and set the startup project.
It worked for me to create the migration in EFCore.
Read this article: https://learn.microsoft.com/en-gb/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
The tooling tries to create a design-time DB context instance using various methods. One of those methods is to look for an implementation of the IDesignTimeDbContextFactory.
Some of the EF Core Tools commands (for example, the Migrations
commands) require a derived DbContext instance to be created at design
time in order to gather details about the application's entity types
and how they map to a database schema. In most cases, it is desirable
that the DbContext thereby created is configured in a similar way to
how it would be configured at run time.
Here's how your DB context factory class might look like:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> {
public BlazorContext CreateDbContext(string[] args) {
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlite("Filename=db.sqlite3");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
I faced the same problem in .Net 6
Make sure that AddDBContext is above builder.Build
builder.Services.AddDbContext<DatabaseDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"))
);
var app = builder.Build();
In the Program.cs file, do not write anything with builder.Services.... below
var app = builder.Build()
line otherwise it throughs an error.
Although OP faced the issue seemingly due incorrect usage of base classes provided by AspNet Identity, but usually we come across this error when an instance of ApplicationDbContext could not be created at design time. There are couple of solutions for this. One of them is to specify the ApplicationDbContext provider in ConfigureServices method in StartUp class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
});
}
For other solutions, please have a look at this link: https://learn.microsoft.com/en-gb/ef/core/miscellaneous/configuring-dbcontext#onconfiguring
I was getting the same error....except the code was working fine just minutes before.
I was in the process of replacing some property attributes with Fluent API
I had three projects: WebApp, DataAccess Library and Model Library.
After trying a few unsuccessful stabs at messing with migrations...I ended up doing a Build->Clean Solution and doing a build on the WebApp.
Every thing was working again...and I could not recreate the error.
This error happened to me, but at the same time I also had a An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not parse the JSON file.
Fixing my appsettings.json file resolved the issue.
I had the same error, just modify the program class. Net Core 3.0
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
To
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
In my case, this was due to me storing my data types and migrations in a separate "Data" project and accidentally having it set as a startup project rather than my actual startup project.
Getting the same error...
Here's how I got there: Created a new ASP.NET Core Web App
(Model-View-Controller) Target Framework was .NET Core 3.1
(LTS) Authentication Type: Individual Accounts
Once the project was created...I wanted to be able to modify the register/login process.(but these pages are part of the Razor Class Library)
So to get the pages in the project: I right click the project Add->New Scaffolded Item...
And picked Identity...
Next I needed to Add-Migration InitIdentity...and this is where the errors/trouble starts.
I tried reading and working through some of the other answers with no success.
I found a solution by:
Creating the project like (above)
But this time I decided NOT to Scaffold Identity.(yet)
I put a connection string in the application.config and ran the project.
I did this before Add-Migration.
I went in to register...A screen came up and said the migration hasnt run yet and had a button to run the migration. I press it and did a refresh and all was good.
Its at this point I went back to the project and did a Add->Scafolded Item...and now there is no error and I have the Auth screens to modify.
Thoroughly inspect your appsettings file and endure it is well formed. Lookout fro missing characters or unnecessary characters
In my case I was using a custom IdentityErrorDescriber :
services.AddIdentity<AppIdentityUser, AppIdentityRole>()
.AddErrorDescriber<MyIdentityErrorDescriber>() // comment this !
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
and in my MyIdentityErrorDescriber I was using resources to translate errors.
and when I comment out the .AddErrorDescriber<MyIdentityErrorDescriber>() line the migration worked without any errors. I think the problem is either with the IdentityErrorDescriber or Resources.
I had three projects, one with Api, second with Models and third with ApplicationDbContext. Api project was starting project. I've added Microsoft.EntityFrameworkCore.Design nuget package to Api project (it's the starting project) and problem solved.
I faced the same error and when I added this it worked fine:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
services.AddScoped<IuserRepositorhy, UserRepository>();
I had two Configurations for Connection Strings in the app settings file, both missing a comma to separate both. When I put the comma, the error was gone.
This might not be your issue, but this is what caused the error on my end. If your app loads an environment variable at build time, that variable should be declared in the terminal. In my case, my app loaded my GOOGLE_APPLICATION_CREDENTIALS from a json file. I needed to export that variable before running anything related to build.
In my case, I built my project and it worked. So try to do this easy step before anything else.
For future reference, a simple gotcha, has got me before.
Make sure you actually have a value inside of the connection string in your appsettings.json file.
I.e.
This will throw an error:
"ConnectionStrings": {
"ConnectionString": ""
},
This will not:
"ConnectionStrings": {
"ConnectionString": "Server=server;Database=db;User Id=user;Password=password!;"
},
In my case, this error ocurred when i copied a project from tutorial repository. I managed to solve it by updating the project packages through NuGet Package Manager.
I'm attempting to connect to my ASP.NET Core Web API application (.NET 6 in Visual Studio 2022 Preview) with SQL Server. And I tried to use the following code to configure the connection string in the Startup class as I used to.
services.AddDbContext<DEMOWTSSPortalContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
But in .NET 6, I recognize that Startup and Program classes are merged into one class. And the above code is not usable in .NET 6. AddDbContext is not recognized. So do you have any idea or documentation about this update, and how to configure connection strings in .NET 6?
Configuration.GetConnectionString(string connName) in .NET6 is under builder:
var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");
also AddDbContext() is under builder.Services:
builder.Services.AddDbContext<YourContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
.Net 6 Simplifies a lot of a tasks and introduces WebApplicationBuilder which in turn gives you access to the new Configuration builder and Service Collection
var builder = WebApplication.CreateBuilder(args);
Properties
Configuration : A collection of configuration providers for the application to compose. This is useful for adding new configuration sources and providers.
Environment : Provides information about the web hosting environment an application is running.
Host : An IHostBuilder for configuring host specific properties, but not building. To build after configuration, call Build().
Logging : A collection of logging providers for the application to compose. This is useful for adding new logging providers.
Services : A collection of services for the application to compose. This is useful for adding user provided or framework provided services.
WebHost : An IWebHostBuilder for configuring server specific properties, but not building. To build after configuration, call Build().
To add a DbContext to the Di Container and configure it, there are many options however the most straightforward is
builder.Services.AddDbContext<SomeDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
Nugets packages
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer to use UseSqlServer
You can try to read in your controller like this..
private readonly IConfiguration _configuration;
public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
{
_logger = logger;
string _configuration = configuration.GetSection("connectionStrings").GetChildren().FirstOrDefault(config => config.Key == "Title").Value;
}
NOTE: You can get the value based on the key provided above.
Install Packages
Microsoft.Extensions.Configuration.dll
Microsoft.Extensions.Configuration.FileExtensions.dll
Microsoft.Extensions.Configuration.Json.dll
Add Name Spaces in Controller
using Microsoft.Extensions.Configuration;
using System.IO;
Add Code in
Controllervar objBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);
IConfiguration conManager = objBuilder.Build();
var my = conManager.GetConnectionString("DefaultConnection");
In appsettings.json Add Code:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
I am using EF core SQLite In memory for unit testing.
I want to see the query is generated by LINQ like SQL Profiler so that I could optimize the query.
Is there any way to check the query?
Refer to this link for full explanation: Logging - EF Core
If you want to log to console: Install package Microsoft.Extensions.Logging.Console
dotnet add package Microsoft.Extensions.Logging.Console
Then create a logger factory implementation:
public static readonly ILoggerFactory MyLoggerFactory
= LoggerFactory.Create(builder => { builder.AddConsole(); });
Then, in your DbContext onConfiguring overrid method, add the .UseLoggerFactory call:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLoggerFactory(MyLoggerFactory) // Warning: Do not create a new ILoggerFactory instance each time
.UseSqlServer(
#"Server=(localdb)\mssqllocaldb;Database=EFLogging;Trusted_Connection=True;ConnectRetryCount=0");
Two options
dotnet ef migrations script
dotnet ef migrations script 20190725054716_Add_new_tables 20190829031257_Add_another_table
You can pipe the output to a file if you want. Beyond this you need to also post the Unit test functions.
Hope it helps
In Visual Studio, click on View/SQL Server Object Explorer and check your Tables if its populating. If not, then you have to add scaffolding.
Right click on the Project/Add/New Scaffold/MVC Controller with views, using EF.
Check this link. https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-3.1&tabs=visual-studio
I face the following error when adding the migration of database in .net core
This is the error:
This is the code in Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllers();
}
This is the ApplicationDbContext class:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
public DbSet<ApplicationUser> applicationUsers { get; set; }
}
This is the ApplicationUser:
public class ApplicationUser : IdentityUser
{
[Required]
[Column(TypeName = "nvarchar(150)")]
public string UserFName { get; set; }
[Required]
public string UserLName { get; set; }
}
I found the cause of this error could be multiple things in your code. For me at least, the best way was to add verbose in command.
With that will be able to understand what is the problem. the verbose will display all steps of the execution.
In visual studio use:
add-migration Added_something -verbose
For the CLI use:
dotnet ef migrations add Added_something --verbose
This error can also occur if multiple startup projects is selected. I set my webproject to startup project and that solved the issue for me.
My problem was solved by installing Microsoft.EntityFrameworkCore.Design nuget package.
this package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct.then install the package.
at the end Build -> Clean Solution in your project and then try running your command again.
Help Link
add migration command cli:
dotnet ef migrations add InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
update database command cli:
dotnet ef database update InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
remove migration command cli:
dotnet ef migrations remove --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
Entity Framework Core tools reference - .NET Core CLI
I also had same problem today when I was running the dotnet ef migrations add <MigrationName>
I had three project, MainApp (Web), C# Project with DBContext and C# Project for Models.
I was able to resolve it from CLI.
dotnet ef migrations add AddCategoryTableToDb -s MainApp -p ProjectHavingDbContext
I had the same error when I had two constructors of my DbContext. After rearranging constructors order to parameterless constructor being first in the class fixed it. e.g.
public ProgramDbContext() : base()
{
}
public ProgramDbContext(DbContextOptions<ProgramDbContext> options) : base(options)
{
}
It must be something with dynamic DbContext object invocation with Reflection playing here.
This error also can occur if you remove the static IHostBuilder CreateHostBuilder(string[] args) method from Program.cs for your .net core app. (This was my case)
Seems you are your inheritance is wrong.
public ApplicationDbContext : IdentityDbContext
should be
public ApplicationDbContext : IdentityDbContext<ApplicationUser>
or
public ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole>
if you also extend roles class.
when you want to create an context with an extended user class (instead of IdentityUser)
Try This one as of March 2021 - VS 16.9.2
I tried many of the above answers and none worked for me. My issue was that we had multiple startup projects, so that was step one. Just set a single startup project, so I set our Data project to be the startup. Still got the error. Then it hit me (thanks to the #AFetter's answer) the Data project does NOT have a connection string within it. So I set my startup project to one with an appSettings.json file that HAS a connection to the DB and then made sure the Package Manager Console's Default Project was set to the Data project and reran the command to create the migration and it worked!
If you come to this issue while using .Net 6 along with the new minimal hosting model, check that you're not calling builder.build() before calling the AddDbContext on builder.services.
using MyProject.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
string relativePath = ".";
string databasePath = Path.Combine(relativePath, "MyDb.sqlite");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite($"Data Source={databasePath}") //connection string
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
I found I was missing:
Microsoft.EntityFrameworkCore.Tool
Microsoft.EntityFrameworkCore.Design
I had multiple startup projects (different API's).
I was at a different level in the PM console.
Then I learned I had to close SQL management so I can run PM console commands.
I was facing the same issue while running the dot net ef migrations script command from the azure pipeline task. I did added "-project" argument. But still was failing.
Adding the "-startup-project" argument worked for me.
I guess even though we specify startup class in project , for ef tool to find one we have to explicitly mention them.
In my case, I was missing a property in appsettings.json that was showing as Warning instead of Error
This error message is sometimes not directly related to the db context model. Check other errors in your Startup class such as missing properties/ credentials in your appsettings.json/ appsettings.Development.json
run your migration with the --verbose option to see all errors and warnings
dotnet ef migrations add YourMigrationName --verbose
If you are using Docker-Compose project. You need to unload the Docker-Compose project and then clean and rebuild the solution and set the startup project.
It worked for me to create the migration in EFCore.
Read this article: https://learn.microsoft.com/en-gb/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
The tooling tries to create a design-time DB context instance using various methods. One of those methods is to look for an implementation of the IDesignTimeDbContextFactory.
Some of the EF Core Tools commands (for example, the Migrations
commands) require a derived DbContext instance to be created at design
time in order to gather details about the application's entity types
and how they map to a database schema. In most cases, it is desirable
that the DbContext thereby created is configured in a similar way to
how it would be configured at run time.
Here's how your DB context factory class might look like:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> {
public BlazorContext CreateDbContext(string[] args) {
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlite("Filename=db.sqlite3");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
I faced the same problem in .Net 6
Make sure that AddDBContext is above builder.Build
builder.Services.AddDbContext<DatabaseDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"))
);
var app = builder.Build();
In the Program.cs file, do not write anything with builder.Services.... below
var app = builder.Build()
line otherwise it throughs an error.
Although OP faced the issue seemingly due incorrect usage of base classes provided by AspNet Identity, but usually we come across this error when an instance of ApplicationDbContext could not be created at design time. There are couple of solutions for this. One of them is to specify the ApplicationDbContext provider in ConfigureServices method in StartUp class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
});
}
For other solutions, please have a look at this link: https://learn.microsoft.com/en-gb/ef/core/miscellaneous/configuring-dbcontext#onconfiguring
I was getting the same error....except the code was working fine just minutes before.
I was in the process of replacing some property attributes with Fluent API
I had three projects: WebApp, DataAccess Library and Model Library.
After trying a few unsuccessful stabs at messing with migrations...I ended up doing a Build->Clean Solution and doing a build on the WebApp.
Every thing was working again...and I could not recreate the error.
This error happened to me, but at the same time I also had a An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not parse the JSON file.
Fixing my appsettings.json file resolved the issue.
I had the same error, just modify the program class. Net Core 3.0
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
To
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
In my case, this was due to me storing my data types and migrations in a separate "Data" project and accidentally having it set as a startup project rather than my actual startup project.
Getting the same error...
Here's how I got there: Created a new ASP.NET Core Web App
(Model-View-Controller) Target Framework was .NET Core 3.1
(LTS) Authentication Type: Individual Accounts
Once the project was created...I wanted to be able to modify the register/login process.(but these pages are part of the Razor Class Library)
So to get the pages in the project: I right click the project Add->New Scaffolded Item...
And picked Identity...
Next I needed to Add-Migration InitIdentity...and this is where the errors/trouble starts.
I tried reading and working through some of the other answers with no success.
I found a solution by:
Creating the project like (above)
But this time I decided NOT to Scaffold Identity.(yet)
I put a connection string in the application.config and ran the project.
I did this before Add-Migration.
I went in to register...A screen came up and said the migration hasnt run yet and had a button to run the migration. I press it and did a refresh and all was good.
Its at this point I went back to the project and did a Add->Scafolded Item...and now there is no error and I have the Auth screens to modify.
Thoroughly inspect your appsettings file and endure it is well formed. Lookout fro missing characters or unnecessary characters
In my case I was using a custom IdentityErrorDescriber :
services.AddIdentity<AppIdentityUser, AppIdentityRole>()
.AddErrorDescriber<MyIdentityErrorDescriber>() // comment this !
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
and in my MyIdentityErrorDescriber I was using resources to translate errors.
and when I comment out the .AddErrorDescriber<MyIdentityErrorDescriber>() line the migration worked without any errors. I think the problem is either with the IdentityErrorDescriber or Resources.
I had three projects, one with Api, second with Models and third with ApplicationDbContext. Api project was starting project. I've added Microsoft.EntityFrameworkCore.Design nuget package to Api project (it's the starting project) and problem solved.
I faced the same error and when I added this it worked fine:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
services.AddScoped<IuserRepositorhy, UserRepository>();
I had two Configurations for Connection Strings in the app settings file, both missing a comma to separate both. When I put the comma, the error was gone.
This might not be your issue, but this is what caused the error on my end. If your app loads an environment variable at build time, that variable should be declared in the terminal. In my case, my app loaded my GOOGLE_APPLICATION_CREDENTIALS from a json file. I needed to export that variable before running anything related to build.
In my case, I built my project and it worked. So try to do this easy step before anything else.
For future reference, a simple gotcha, has got me before.
Make sure you actually have a value inside of the connection string in your appsettings.json file.
I.e.
This will throw an error:
"ConnectionStrings": {
"ConnectionString": ""
},
This will not:
"ConnectionStrings": {
"ConnectionString": "Server=server;Database=db;User Id=user;Password=password!;"
},
In my case, this error ocurred when i copied a project from tutorial repository. I managed to solve it by updating the project packages through NuGet Package Manager.
I am on a Mac using dotnet Core 2.0
I would like to use a different database on my local development machine, like sqlite and SQL Server on staging and production.
I can have the following appsettings.json files: appsettings.Development.json, appsettings.Staging.json, and appsettings.json for development, staging, and production respectively.
In each of the files I want a different database like sqlite for development and SQLServer for staging and production, including different migrations.
My development environment is set to Development via an environment variable. When I run dotnet run I can confirm the hosting environment is Hosting environment: Development
In my program.cs file I have the following code
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
I have a class called StartupDevelopment
public class StartupDevelopment
{
public StartupDevelopment(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<MvcTriviaContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("dbContext")));
}
}
When I debug my application the constructor of the class Starup is called instead of StartupDevelopment.
Now I do not want to change program.cs because then i would have to change that for each environment.
I want the code to use StartupDevelopment when my environment is set to Development.
Documentation says
An alternative to injecting IHostingEnvironment is to use a
conventions-based approach. The app can define separate Startup
classes for different environments (for example, StartupDevelopment),
and the appropriate startup class is selected at runtime.
I don't understand what am I doing wrong? How do I make the app use StartupDevelopment when my environment is Development.
I'm on Windows, and I get the same behavior that you are seeing.
What worked was changing UsesStartup<Startup> to UsesStartup(typeof(Startup).Assembly.FullName) in Program.cs. The documentation is not clear about this, but I think if you specify a startup type that forces Asp.Net Core to use that type and not use conventions for finding the startup type.
Instead of using StartupDevelopment it is better to use ConfigureDevelopmentServices method in Startup.cs. This way our program.cs remains untouched and this solution works with dotnet aspen-codegenerator when creating controllers.