Reputation: 3384
Using EF Core 2.0 i am trying to implement IDesignTimeDbContextFactory to read connection string from the appsettings.json file. I am getting following error on call to SetBasePath
ConfigurationBuilder does not contain a definition of SetBasePath( )
public class DbContextFactory : IDesignTimeDbContextFactory<TestDbContext>
{
public TestDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<TestDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new TestDbContext(builder.Options);
}
}
Second Question : Using this approach is it necessary to use dotnet CLI, will this method be called if i am just running my migration commands using "Package Manager Console" ?
Upvotes: 0
Views: 1229
Reputation: 885
The SetBasePath()
method is an extension method in FileExtensions.
You can get it by adding the Microsoft.Extensions.Configuration.FileExtensions
package. I see you have AddJsonFile()
also, so you might want to use Microsoft.Extensions.Configuration.Json
instead since it depends on FileExtensions
(i.e you'll get both).
On the 2nd question, you don't need the IDesignTimeDbContextFactory<>
, but without if you'll need to set the connection string in another place that is accessible during design time. Another example is to set it in the constructor of your DbContext
, but that has various design problems like if you want to run a test vs production instance.
If you don't have a factory the DbContext
is created using a public parameterless constructor.
Upvotes: 2