I have separated my Database project as a class library. And I am defining a IDesignTimeDbContextFactory
implementation. I want to use user-secrets
to keep the config settings. I get an error as follows. How can i make this setup work?
Note: I have already setup the user-secrets for the class library project. And my user secrets has the necessary values:
{
"ConnectionStrings:CatalogDbContext": "Server=(localdb)\\\\mssqllocaldb;Database=Catalog;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Project Structure:
Catalog
|---API(Web API)
|---Data(Class Lib)
|- appsettings.json
|- IDesignTimeDbContextFactory<CatalogDbContext>
Appsettings.json
{
"ConnectionStrings": {
"CatalogDbContext": ""
}
}
public class CatalogDbContextFactory : IDesignTimeDbContextFactory<CatalogDbContext>
{
public CatalogDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var dbContextOptionsBuilder = new DbContextOptionsBuilder<CatalogDbContext>();
var connectionString = configuration.GetConnectionString(nameof(CatalogDbContext));
dbContextOptionsBuilder
.UseSqlServer(connectionString);
return new CatalogDbContext(dbContextOptionsBuilder.Options);
}
}
This command fails with an error:
Catalog.Api> dotnet ef migrations add Catalog.Initial --project ..\Catalog.Data\Catalog.Data.csproj --verbose
Finding DbContext classes in the project...
Found DbContext 'CatalogDbContext'.
Using DbContext factory 'CatalogDbContextFactory'.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
I can clearly say this is because the connectionstring is empty. The user secrets configuration provided is not added to the list of providers. I don't know what the setup will look like to add user secrets to a class library project. Please help!
CodePudding user response:
I tried as you mentioned and repeated your error in my case
then I modified the appsettings.json in webapi project and added the migration successfully this time,it still read the jsonfile in your webapi project