dotnet datacontext not able to migrate [duplicate] - c#
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.
Related
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.
Error running update-database entityframeworkcore 2
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
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
Specifying HostingEnvironment when running EF 7 migration
I have set my connection strings for my DbContexts as per my application environment. So in my Startup.cs I have public Startup(IHostingEnvironment env, IApplicationEnvironment app) { Configuration = new ConfigurationBuilder(app.ApplicationBasePath) .AddJsonFile("config.json") .AddJsonFile($"config.{env.EnvironmentName}.json", false) .AddEnvironmentVariables() .Build(); } This configuration gets injected into my DbContexts as follows public MyDbContext(IConfiguration configuration) { Configuration = configuration; } protected override void OnConfiguring(DbContextOptionsBuilder builder) { var connString = Configuration.Get("SqlDb:ConnectionString"); builder.UseSqlServer(connString); } And thus I can use my project in various environments as I please (by setting ASPNET_ENV in app or host settings) However when I run ef migrations (for obvious reasons) I cant specify the HostingEnvironment at all, the startup class looks for a file called "config..json" since the environment name is missing. Is there a way around this or a workaround that I can do? For now whenever I run migrations I have to hardcode the connection strings when I run migrations For interest sake I run migrations from powershell using the dnx . ef command So in summary is it possible to specify my host environment via the command or do any other kind of workaround to specify my environment when running these commands?
How migrations discovers services for migrations will be changing in upcoming versions of EF. This is a WIP. See EF7's Wiki - Design Meeting Notes (September 17, 2015) and Issue 2294
The --environment option was added with 7f48d0c.