Error running update-database entityframeworkcore 2 - c#

I have EntityFrameworkCore 2.0.2 installed in a class library on a solution containing an AspNet Core WebApi.
I have the following packages installed in the project;
Microsoft.AspNetCore.Identity.EntityFrameworkCore - 2.0.2
Microsoft.EntityFrameworkCore - 2.0.2
Microsoft.EntityFrameworkCore.SqlServer - 2.0.2
Microsoft.Extensions.Identity.Stores - 2.0.2
System.Data.SqlClient - 4.4.3
My Class library project invokes the context as follows;
public class MyContextFactory : IDesignTimeDbContextFactory<MyDataContext>
{
public MyContextFactory()
{
}
public MyDataContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<MyDataContext>();
builder.UseSqlServer(DbGlobals.DevDatabase);
return new MyDataContext(builder.Options);
}
}
I am getting the following error, when I try to run the update-database command from the package manager console.
Application startup exception: System.IO.FileNotFoundException: Could
not find file
'C:\Users\matt\Source\Repos\project\Services.WebApi\bin\Debug\netcoreapp2.0\ef.xml'.
this now occurs when I try to add-migration as well.
I can't find any detail on ef.xml and how it is generated? Can anyone tell me what is going on here.
If I run an add-migration i get the migration generated, but then get the error;
An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Could not find file 'C:\Users\matt\Source\Repos\project\Services.WebApi\bin\Debug\netcoreapp2.0\ef.xml'.
I have tried cleaning the project, re-compiling (there are no errors), I have also looked in the referenced folder and the file doesn't exist. Nor (from a file search) has it been generated elsewhere?
The migrations have been working fine now?
Per request my BuildwebHost is;
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
and I add EF in my Startup.cs;
services.AddDbContext<MyDataContext>(
options => options
.UseSqlServer(DbGlobals.DevDatabase));

The commands you are using update-database and add-migration donĀ“t look like the supported Entity Framework Core CLI commands:
dotnet ef add migrations <migration-name>
dotnet ef database update
Also check this SO question for further information:
Entity Framework Core 2.0 add-migration not generating anything

Related

dotnet datacontext not able to migrate [duplicate]

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.

Pass different connection strings to IDesignTimeDbContextFactory using Azure Functions with .NET 5 (Isolated)

I have created a new FunctionApp in Visual Studio Version 16.10.0 using the template Azure Functions with .NET 5 (Isolated) and Http trigger.
Following the guide for Design-time DbContext Creation it seems I can only use IDesignTimeDbContextFactory and not application services. I have created a separate question for using HostBuilder.
https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=vs
Microsoft.EntityFrameworkCore.Tools - Azure Functions with .NET 5 (Isolated) Design-time DbContext Creation with HostBuilder
Getting the connection string from Environment.GetEnvironmentVariable is not a problem at runtime:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:DefaultConnection");
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(connectionString);
return new ApplicationDbContext(optionsBuilder.Options);
}
}
local.settings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=FunctionApp1.Test;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
}
}
Function1cs:
var applicationDbContextFactory = new ApplicationDbContextFactory();
using var context = applicationDbContextFactory.CreateDbContext(null);
However using Microsoft.EntityFrameworkCore.Tools Add-Migration InitialCreate in Package Manager Console I get the following error:
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.ArgumentNullException:
Value cannot be null. (Parameter 'connectionString')
This is expected since environment variables are not present when running via Package Manager Console. I can not use code like this either:
$ConnectionStrings.DefaultConnection="Server=tcp:mySqlServerStuffxxx"
Add-Migration InitialCreate
Will result in the following error:
The property 'DefaultConnection' cannot be found on this object.
Verify that the property exists and can be set.
https://stackoverflow.com/a/67822243/3850405
I can load a connection string like this but in production I would like a different value. Works a lot better with appsettings.json that gets deployed and checked in by default.
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json")
.Build();
var connectionString = configuration.GetConnectionString("DefaultConnection");
https://stackoverflow.com/a/52418717/3850405
I then tried to use -Args as mentioned in MS Docs.
https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=vs#args
var connectionString = args[0];
With this I could add a new migration and it looked good.
Add-Migration InitialCreate -Args 'Server=(localdb)\\mssqllocaldb;Database=FunctionApp1.Test;Trusted_Connection=True;MultipleActiveResultSets=true'
However when running Update-Database it fails with the following error:
Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related
or instance-specific error occurred while establishing a connection to
SQL Server. The server was not found or was not accessible. Verify
that the instance name is correct and that SQL Server is configured to
allow remote connections. (provider: SNI_PN11, error: 50 - Local
Database Runtime error occurred. Specified LocalDB instance name is
invalid.
Update-Database -Args 'Server=(localdb)\\mssqllocaldb;Database=FunctionApp1.Test;Trusted_Connection=True;MultipleActiveResultSets=true'
If I either hard code the exact same value or get the value from ConfigurationBuilder everything works with these settings.
var connectionString = "Server=(localdb)\\mssqllocaldb;Database=FunctionApp1.Test;Trusted_Connection=True;MultipleActiveResultSets=true";
Which is the best way to pass different connection strings to IDesignTimeDbContextFactory that works both at runtime and Package Manager Console?
Given that the solution with ConfigurationBuilder works without duplicating the connection string we decided to use that solution and then only use ApplicationDbContextFactory for design and never in code.
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json")
.Build();
var connectionString = configuration.GetConnectionString("DefaultConnection");
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(connectionString);
return new ApplicationDbContext(optionsBuilder.Options);
}
}
Then got another error when Entity Framework was moved to its own class library.
Your target project 'FunctionApp1.FunctionApp' doesn't match your
migrations assembly 'FunctionApp1.EntityFramework'. Either change your
target project or change your migrations assembly. Change your
migrations assembly by using DbContextOptionsBuilder. E.g.
options.UseSqlServer(connection, b =>
b.MigrationsAssembly("FunctionApp1.FunctionApp")). By default, the
migrations assembly is the assembly containing the DbContext. Change
your target project to the migrations project by using the Package
Manager Console's Default project drop-down list, or by executing
"dotnet ef" from the directory containing the migrations project.
Solved this by setting Default Project in PMC as the Entity Framework project and Startup project as the project containing local.settings.json.

Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time

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.

Create EF Core as separate project in Visual Studio 2017

I'm trying to create a separate EF Core 2 as separate project.
I created a class library (.net core), add two references: Microsoft.EntityFrameworkCore, Microsoft.EntityFrameworkCore.Design
Then I met an error like:
The specified framework 'Microsoft.NETCore.App', version '2.0' was not found
I solved by adding in root folder a json file called global.json which content is:
{
"sdk": {
"version": "2.0.2"
}
}
Good until here.
If I run command: dotnet ef update database it tells that:
No database provider has been configured for this DbContext.
Most of people said that I have to register in Startup.cs. But I don't have it because the project is class library, no mvc core application.
So, what steps to do in this case ?
Of course, I have a separate project for mvc core which has reference to that EF core project. Should I register the dbcontext in that Startup.cs file ?
Assuming nothing had changed in the last few weeks since I did this:
Create class DesignTimeDbContextFactory (replacing ApplicationDbContext with the name of your DbContext:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var connectionString = "Server=(localdb)\\mssqllocaldb;Database=MyDbName;Trusted_Connection=True;MultipleActiveResultSets=true";
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
builder.UseSqlServer(connectionString);
return new ApplicationDbContext(builder.Options);
}
}
Now do one of the following:
if using the Add-Migration and Update-Database commandlets use the -project [project-name] flag
if using dotnet from command line use the --project [project-name] flag
or you can ensure that this class library is set as startup project and also set in the PM console the 'Default Project' and then add your migrations and update the database

Entity Framework Core 2.0 Add-Migration doesn't create any migration files

Recently migrated from EF Core 1.0 to EF Core 2.0, and it runs fine. Today I added a new table (code-first) and added it to my DbContext with:
public virtual DbSet<Foo> Foos { get; set; }
When I run a migration, with my DbContext in a separate project (remember this was all working before), the migration ends, but no migration files were created. This was all working prior to Core 2.0 using:
http://paultechguy.blogspot.com/2017/04/entity-framework-core-migrating-and.html
PM> Add-Migration GradePremade -project Mfc.MfcRepositoryModel -verbose -context MfcDbContext -StartupProject web.xyz
Using project 'class.xyz\Mfc.MfcRepositoryModel'.
Using startup project 'web.xyz'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\development\xyz\web.xyz\bin\Debug\netcoreapp2.0\web.xyz.deps.json --additionalprobingpath C:\Users\pcarver\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig C:\development\xyz\web.xyz\bin\Debug\netcoreapp2.0\web.xyz.runtimeconfig.json "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.entityframeworkcore.tools\2.0.0\tools\netcoreapp2.0\ef.dll" migrations add GradePremade --json --context MfcDbContext --verbose --no-color --prefix-output --assembly C:\development\xyz\web.xyz\bin\Debug\netcoreapp2.0\Mfc.MfcRepositoryModel.dll --startup-assembly C:\development\xyz\web.xyz\bin\Debug\netcoreapp2.0\web.xyz.dll --project-dir C:\development\xyz\class.xyz\Mfc.MfcRepositoryModel --root-namespace Mfc.MfcRepositoryModel
Using assembly 'Mfc.MfcRepositoryModel'.
Using startup assembly 'web.xyz'.
Using application base 'C:\development\xyz\web.xyz\bin\Debug\netcoreapp2.0'.
Using working directory 'C:\development\xyz\web.xyz'.
Using root namespace 'Mfc.MfcRepositoryModel'.
Using project directory 'C:\development\xyz\class.xyz\Mfc.MfcRepositoryModel'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding BuildWebHost method...
No BuildWebHost method was found on type 'xyz.Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'ApplicationDbContext'.
Found DbContext 'MfcDbContext'.
Using DbContext factory 'MfcContextFactory'.
Using context 'MfcDbContext'.
Finding design-time services for provider 'Microsoft.EntityFrameworkCore.SqlServer'...
Using design-time services from provider 'Microsoft.EntityFrameworkCore.SqlServer'.
Finding IDesignTimeServices implementations in assembly 'web.xyz'...
No design-time services were found.
No errors that seem obvious to me, and no migration files created. I've done a Remove-Migration to start clean, but still no workie.
There is an issue within the .NET Core class libraries. The successful workaround is to put the following in the csproj file of the Model project:
<PropertyGroup>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
</PropertyGroup>
I had to mark a project as the start-up project.
You will need to update your Program class to look like this
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
host.Run();
}
// Tools will use this to get application services
public static IWebHost BuildWebHost(string[] args) =>
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
I had a similar problem but none of the provided answers fixed it. After reviewing my .csproj-file, I found that Visual Studio automatically added the following lines at some point:
<ItemGroup>
<Compile Remove="Migrations\**" />
<Content Remove="Migrations\**" />
<EmbeddedResource Remove="Migrations\**" />
<None Remove="Migrations\**" />
</ItemGroup>
After removing this ItemGroup, updating my database worked correctly again.
Remove all your IDesignTimeDbContextFactory<TContext> implementations from your migrations project and register your DbContext in your ConfigureServices method in your startup class, the same way you would register when running the application.
Then run your migrations commands as usual, this worked for me after hours of headaches.
Just try to review the migrations ModelSnapshot.cs file, for differences in the name of a table, creations of relationships (at the end of the code).
DbContext class should have parametrless constructor and constructor with options. You have to Override OnConfiguring. Inside of it specified provider for exaple:
options.UseSqlServer(_connectionString);
Code sample:
public class AppDbContext : DbContext
{
private const string _connectionString = "Data Source=....;App=EntityFramework";
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{ }
public AppDbContext() : base()
{
}
public virtual DbSet<MyEntitie> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (options.IsConfigured)
{
return;
}
options.UseSqlServer(_connectionString);
}
}
At the end use command line and run this command (type file name of project where is your DbContext file), alternativly you can use nuget package manager console:
dotnet ef migrations -v -p App.csproj add Init
I tried updating the runtime version in the .csproj file to include:
<RuntimeFrameworkVersion>2.0.3</RuntimeFrameworkVersion>
in the PropertyGroup tag. It worked for me.
See: Russell Seamer's Solution

Categories

Resources