I am trying to build your sample. I’ve removed all the projects down to the Test Web App Core and have added the latest SAML 2 and SAML 2 MVC packages from NuGet. I am getting a compiler error (see below). Services.BindConfig does not exist.
Any help would be appreciated.
......
namespace TestWebAppCore
{
public class Startup
{
public static IWebHostEnvironment AppEnvironment { get; private set; }
public Startup(IWebHostEnvironment env, IConfiguration configuration)
{
AppEnvironment = env;
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
**services.BindConfig**<Saml2Configuration>(Configuration, "Saml2", (serviceProvider, saml2Configuration) =>
{
I've downloaded the ITFOXTEC SAML2 example project from github and am trying to get it to work
EDIT: I do have the appropriate package & includes.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/T4zKu.png
The problem occur because you are using the wrong SAML 2 MVC package, you need to use the ITfoxtec.Identity.Saml2.MvcCore package. And add a using statement for the namespace ITfoxtec.Identity.Saml2.MvcCore.
I had the same issue and solved it. The newest NuGet release is 3/24/22. BindConfig support was added later on 6/1/22. So if you want to use the version that's in NuGet, just select the next oldest version of the test app in GitHub to get the code that doesn't use BindConfig. For the TestWebAppCore Startup.cs file it's https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2/blob/d31f7a1b1ff9251810a4fcef8ac2dc920e2a94ef/test/TestWebAppCore/Startup.cs
Was trying to follow a tutorial here for a console app https://www.connectionstrings.com/store-and-read-connection-string-in-appsettings-json/
So in my appsettings-json i have:
{
"ConnectionStrings": {
"myDb1": "Server=myServer;Database=myDb1;Trusted_Connection=True;",
}
}
My program:
using System;
using Microsoft.Extensions.Configuration;
namespace mynamespace
{
class Program
{
string myDb1ConnectionString = _configuration.GetConnectionString("myDb1");
static void Main(string[] args)
{
...
}
}
}
The error I get is : "The name '_configuration' does not exist in the current context".
The page you link to isn't a tutorial, it only shows how to read a connection string from any configuration provider, not just appsettings.json. It assumes you've already built a configuration object. .NET (Core) 5 and 6 use far simpler code though.
Check Configuration in .NET to understand how configuration really works. You can find more detailed information on the various config providers, how they're used and how to create your own in Configuration in ASP.NET Core
Using a generic host
In .NET 6, the current long term version, a minimal application would need:
using Microsoft.Extensions.Hosting;
using IHost host = Host.CreateDefaultBuilder(args).Build();
var configuration=host.Services.GetRequiredService<IConfiguration>();
var connectionString=configuration.GetConnectionString("blahblah");
...
As the docs explain, CreateDefaultBuilder will load configuration settings from any appsettings.json files, environment variables and finally command-line parameters.
This means you can override the settings stored in the JSON files by specifying the new values using environment variables or CLI parameters, eg :
dotnet run /ConnectionStrings:blahblah="......."
Without a generic host
You can create just the Configuration object by using a ConfigurationBuilder:
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
var connectionString=config.GetConnectionString("blahblah");
I've got a method that reads settings from my config file like this:
var value = ConfigurationManager.AppSettings[key];
It compiles fine when targeting .NET Standard 2.0 only.
Now I need multiple targets, so I updated my project file with:
<TargetFrameworks>netcoreapp2.0;net461;netstandard2.0</TargetFrameworks>
But now, the compilation fails for netcoreapp2.0 with the following error message:
Error CS0103 The name 'ConfigurationManager' does not exist in the current context (netcoreapp2.0)
Separately, I created a new .NET Core 2.0 console application (only targeting .NET Core 2.0 this time), but likewise there seems to be no ConfigurationManager under the namespace System.Configuration.
I'm quite confused because it's available under .NET Standard 2.0, so I would expect it to be available in .NET Core 2.0, as .NET Core 2.0 is .NET Standard 2.0 compliant.
What am I missing?
Yes, ConfigurationManager.AppSettings is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager.
Credits goes to #JeroenMostert for giving me the solution.
I installed System.Configuration.ConfigurationManager from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
Once you have the packages setup, you'll need to create either an app.config or web.config and add something like the following:
<configuration>
<appSettings>
<add key="key" value="value"/>
</appSettings>
</configuration>
The latest set of guidance is as follows: (from https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)
Use:
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
From the docs:
public static class EnvironmentVariablesExample
{
[FunctionName("GetEnvironmentVariables")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
}
public static string GetEnvironmentVariable(string name)
{
return name + ": " +
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
}
App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.
The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.
I used below code example. Also this is so convenient way.
using Microsoft.Extensions.Configuration;
using System.IO;
namespace DemoWeppApp
{
public static class StaticConfigurationManager
{
public static IConfiguration AppSetting { get; }
static StaticConfigurationManager()
{
AppSetting = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
}
}
}
And then I can use easly in any static class like this
StaticConfigurationManager.AppSetting["conf_name"];
You can use Configuration to resolve this.
Ex (Startup.cs):
You can pass by DI to the controllers after this implementation.
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
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)
{
var microserviceName = Configuration["microserviceName"];
services.AddSingleton(Configuration);
...
}
I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app.
in API constructor add the following:
public class TargetClassController : ControllerBase
{
private readonly IConfiguration _config;
public TargetClassController(IConfiguration config)
{
_config = config;
}
[HttpGet("{id:int}")]
public async Task<ActionResult<DTOResponse>> Get(int id)
{
var config = _config["YourKeySection:key"];
}
}
I am trying to learn .Net core.
I have 2 to projects :
.Net Core Web api project
DLL .NetCore project contains my Unit of Work (entity framework)
My Questions:
How I can pass connection string from appsettings.json
to my DLL
I have in startup.cs configuration but I don t how to use it to access to my appsettings.json
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
there is services.AddDbContext in startup.cs
services.AddDbContext(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")))
but I don't want to use services.AddDbContext because is a couple to entity framework and if I have to change to other ORM I have to change
this code also.
other question how have a responsibility to decrypt the connection
string.
a : webapi has to decrypt to the connection string and pass to DLL
(unit of work)
b: or unit of work has to decrypt the connection string
in the case I have another project (ie desktop application) how to
use DLL (unit of work) do I have to put also the connection
string inside my appsettings of the desktop application? (it like
kind of repetition ? )
I don't want to use services.AddDbContext because is a couple of entity framework
So what you need to do is create an extension method in your EF project that wraps this call so the dependency to EF stays within the EF project like the following:
public static IServiceCollection AddDatabase<TContext>( this IServiceCollection serviceCollection, Action<DbContextOptionsBuilder> optionsAction, string connectionString)
{
options.UseSqlServer(connectionString))
}
Then call this from your Startup Code:
services.AddDatabase(Configuration.GetConnectionString("DefaultConnection"));
That will resolve your dependency issue.
Regarding 2: see here: Encrypted Configuration in ASP.NET Core
Regarding 3: then the other projects will need to call the AddDatabase method and pass the connection string in, so the EF project will never have any knowledge about where to get it, it is always provided.
You can do it like this:
public BooksContext(string connectionString): this(GetOptions(connectionString))
{ }
private static DbContextOptions GetOptions(string connectionString)
{
return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}
You can get the in Stratup.cs file like this.
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
private readonly IConfigurationRoot _appConfiguration;
private readonly IHostingEnvironment _hostingEnvironment;
public Startup(IHostingEnvironment env)
{
_hostingEnvironment = env;
_appConfiguration = env.GetAppConfiguration();
}
Code to get ConnectionString:
string connectionString = _appConfiguration["ConnectionStrings:Default"];
appsettings.json
{
"ConnectionStrings": {
"Default": "Server=YourDBAddress; Database=YourDB; Trusted_Connection=True;"
}
...
}
For other points, you can refer #Jamie Rees's answer.
After upgrading to ASP.NET Core 2.0, I can't seem to create migrations anymore.
I'm getting
"An error occurred while calling method 'BuildWebHost' on class
'Program'. Continuing without the application service provider. Error:
One or more errors occurred. (Cannot open database "..." requested by
the login. The login failed. Login failed for user '...'"
and
"Unable to create an object of type 'MyContext'. Add an implementation
of 'IDesignTimeDbContextFactory' to the project, or see
https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns
supported at design time."
The command I previously ran was $ dotnet ef migrations add InitialCreate --startup-project "..\Web" (from the project/folder with the DBContext).
Connection string: "Server=(localdb)\\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"
This is my Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.
Here is the sample code:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
{
public CodingBlastDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new CodingBlastDbContext(builder.Options);
}
}
Then, navigate to your Database project and run the following from command line:
dotnet ef migrations add InitialMigration -s ../Web/
dotnet ef database update -s ../Web/
-s stands for startup project and ../Web/ is the location of my web/startup project.
resource
No need for IDesignTimeDbContextFactory.
Run
add-migration initial -verbose
that will reveal the details under
An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider.
warning, which is the root cause of the problem.
In my case, problem was, having ApplicationRole : IdentityRole<int> and invoking services.AddIdentity<ApplicationUser, IdentityRole>() which was causing below error
System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.
Solution 1: (Find the problem in 99% of cases)
Set Web Application project as Startup Project
Run the following commands with -verbose option.
Add-Migration Init -Verbose
-verbose option helps to actually uncover the real problem, It
contains detailed errors.
Solution 2:
Rename BuildWebHost() to CreateWebHostBuilder(), because Entity Framework Core tools expect to find a CreateHostBuilder method that configures the host without running the app.
.NET Core 2.2
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
.NET Core 3.1
Rename BuildWebHost() to CreateHostBuilder()
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Solution 3:
Make sure you added Dbcontext to dependency injection:
AddDbContext<TContext> will make both your DbContext type, TContext, and the corresponding DbContextOptions<TContext> available for injection from the service container.
This requires adding a constructor argument to your DbContext type that accepts DbContextOptions<TContext>.
Example:
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options => options.UseSqlServer(connectionString));
}
AppDbContext code:
public class AppDbContext: DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
:base(options)
{ }
}
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
Just rename BuildWebHost() to CreateWebHostBuilder(), because migrations use this method by default.
In my case, the cause of the problem was multiple startup projects. I have three projects in my solution: Mvc, Api, and Dal. DbContext and Migrations in the Dal project.
I had configured multiple startup projects. Both Mvc and Api projects were running when I clicked Start. But in this case I was getting this error.
"Unable to create an object of type 'MyContext'. Add an implementation
of 'IDesignTimeDbContextFactory' to the project, or see
https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns
supported at design time."
I could successfully add migration after setting Mvc as the only startup project and selecting Dal in the Package Manager Console.
In the AppContext.cs besides AppContext class add another class:
// required when local database deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
{
public AppContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
return new AppContext(builder.Options);
}
}
This will solve your second problem:
"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project,
After that you will be able to add-migration Initial and execute it by running update-database command.
However if running these commands when there is no DataBase yet in your local SqlServer you will get the warning like your first error: "An error
occurred while calling method 'BuildWebHost' on class 'Program'... The
login failed. Login failed for user '...'"
But it is not error because migration will be created and it can be executed.
So just ignore this error for the first time, and latter since Db will exist it won't happen again.
You can try this solution from this discussion, which was inspired by this post.
public static IWebHost MigrateDatabase(this IWebHost webHost)
{
using (var scope = webHost.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var db = services.GetRequiredService<MyContext>();
db.Database.Migrate();
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
}
}
return webHost;
}
public static void Main(string[] args)
{
BuildWebHost(args)
.MigrateDatabase()
.Run();
}
Something that really helped me was this article: https://elanderson.net/2017/09/unable-to-create-an-object-of-type-applicationdbcontext-add-an-implementation-of-idesigntimedbcontextfactory/
The basic idea is that in the change over from .net core 1 to 2 all db initialization should be moved out of the StartUp.cs and into the Program.cs. Otherwise the EF tasks try and run your DB inits when doing tasks.
"There is a nice section in the official migration docs (https://learn.microsoft.com/en-us/ef/core/miscellaneous/1x-2x-upgrade) titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn’t what is causing your need to add an implementation of IdesignTimeDbContextFactory."
Please verify that you have the reference
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
From
https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
When you create a new ASP.NET Core 2.0 application, this hook is
included by default. In previous versions of EF Core and ASP.NET Core,
the tools try to invoke Startup.ConfigureServices directly in order to
obtain the application's service provider, but this pattern no longer
works correctly in ASP.NET Core 2.0 applications. If you are upgrading
an ASP.NET Core 1.x application to 2.0, you can modify your Program
class to follow the new pattern.
Add Factory in .Net Core 2.x
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
public BloggingContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
}
}
I had this problem and this solved By Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project"
Then run -> add-migration initial -verbose
in Package Manager Console
Set as Startup Project
If you want to avoid those IDesignTimeDbContextFactory thing: Just make sure that you don't use any Seed method in your startup. I was using a static seed method in my startup and it was causing this error for me.
I was facing the error
"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time."
This is how my problem was solved. Run the below command while you are in your solution directory
dotnet ef migrations add InitialMigration --project "Blog.Infrastructure" --startup-project "Blog.Appication"
Here Application is my startup project containing the Startup.cs class & Infrastructure is my project containing the DbContext class.
then run update using the same structure.
dotnet ef database update --project "Blog.Infrastructure" --startup-project "Blog.Application"
Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.
The refactored Main method. Add the following references to the Program.cs:
using Microsoft.Extensions.DependencyInjection;
using MyProject.MyDbContextFolder;
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<MyDbConext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
}
}
host.Run();
}
There's a problem with ef seeding db from Startup.Configure in 2.0 ... you can still do it with this work around. Tested and worked fine
https://garywoodfine.com/how-to-seed-your-ef-core-database/
In my case I got the problem because I had a method named SeedData.EnsurePopulated() being called on my Startup.cs file.
public class Startup
{
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
//
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
//
});
SeedData.EnsurePopulated(app);
}
}
The work of SeedData class is to add initial data to the database table. It's code is:
public static void EnsurePopulated(IApplicationBuilder app)
{
ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
if (!context.Products.Any())
{
context.Products.AddRange(
new Product
{
Name = "Kayak",
Description = "A boat for one person",
Category = "Watersports",
Price = 275
},
....
);
context.SaveChanges();
}
}
SOLUTION
Before doing migration simply comment out the calling of SeedData class in the Startup.cs file.
// SeedData.EnsurePopulated(app);
That solved my problem and hope your problem is also solved in the same way.
I ran into same problem. I have two projects in the solution. which
API
Services and repo, which hold context models
Initially, API project was set as Startup project.
I changed the Startup project to the one which holds context classes.
if you are using Visual Studio you can set a project as Startup project by:
open solution explorer >> right-click on context project >> select Set as Startup project
First of all make sure you have configured your database in Startup.cs
In my case, i was getting this error since i didn't specify the below in Startup.cs
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"), x => x.MigrationsAssembly("<Your Project Assembly name where DBContext class resides>")));
Using ASP.NET Core 3.1 and EntityFrameWorkCore 3.1.0. Overriding the OnConfiguring of the context class with a parameterless constructor only
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("LibraryConnection");
optionsBuilder.UseSqlServer(connectionString);
}
}
I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
After upgrading to the newer version it got resolved
In main project's appsettings.json file, I had set 'Copy to Output directory' to "Copy always" and it worked.
Sample DB context class for .net core console applications
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace EmailServerConsole.Data
{
public class EmailDBContext : DbContext
{
public EmailDBContext(DbContextOptions<EmailDBContext> options) : base(options) { }
public DbSet<EmailQueue> EmailsQueue { get; set; }
}
public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<EmailDBContext>
{
EmailDBContext IDesignTimeDbContextFactory<EmailDBContext>.CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<EmailDBContext>();
var connectionString = configuration.GetConnectionString("connection_string");
builder.UseSqlServer(connectionString);
return new EmailDBContext(builder.Options);
}
}
}
You also can use in the startup class constructor to add json file (where the connection string lies) to the configuration. Example:
IConfigurationRoot _config;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json");
_config = builder.Build();
}
For me it was because I changed the Output Type of my startup project from Console Application to Class Library.
Reverting to Console Application did the trick.
I had this issue in a solution that has:
a .NET Core 2.2 MVC project
a .NET Core 3.0 Blazor project
The DB Context in a .NET Standard 2.0 class library project
I get the "unable to create an object..." message when the Blazor project is set as the start up project, but not if the MVC project is set as the startup project.
That puzzles me, because in the Package Manager Console (which is where I'm creating the migration) I have the Default project set to a the C# class library that actually contains the DB Context, and I'm also specifying the DB context in my call to add-migration add-migration MigrationName -context ContextName, so it seems strange that Visual Studio cares what startup project is currently set.
I'm guessing the reason is that when the Blazor project is the startup project the PMC is determining the version of .NET to be Core 3.0 from the startup project and then trying to use that to run the migrations on the .NET Standard 2.0 class library and hitting a conflict of some sort.
Whatever the cause, changing the startup project to the MVC project that targets Core 2.2, rather than the Blazor project, fixed the issue
For me the problem was that I was running the migration commands inside the wrong project. Running the commands inside the project that contained the Startup.cs rather than the project that contained the DbContext allowed me to move past this particular problem.
In my case setting the StartUp project in init helps. You can do this by executing
dotnet ef migrations add init -s ../StartUpProjectName
Manzur Alahi is right! I'm trying to learn Rider by JetBrains and I had the same error when I was trying to use dotnet-ef migrations add ... in Cmd, PowerShell, etc. but when I used Visual Studio IDE I didn't have problem.
I fixed the error with:
dotnet ef migrations add InitialMigration --project "Domain.Entities" --startup-project "WebApi"
and this to update the database
dotnet ef database update --project "Domain.Entities" --startup-project "WebApi"
just like Manzur Alahi said.
If context class is in another class library project and this error is occurred, change command line default project to the context project and set solution startup project to the main API / ASP.net core project (that your DI container is there), then re-run command
It seems ef core tools package has this bug a reported in
https://github.com/dotnet/efcore/issues/23957 and https://github.com/dotnet/efcore/issues/23853
I had same problem. Just changed the ap.jason to application.jason and it fixed the issue