My solution has 3 project:
- Entity(include Dbcontext,...), target framwork .NetStandard 1.4, project type library
- WebApi
- WebUi
i want to create function migrate into Entity Project. In Entity project, i have a class TemporaryDbContextFactory
public class TemporaryDbContextFactory : IDbContextFactory<MyContext>
{
public ApplicationContext Create(DbContextFactoryOptions options)
{
var builder = new DbContextOptionsBuilder<MyContext>();
builder.UseSqlServer("Server=(local)\\mssqllocaldb;Database=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa; Password=123456",
optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(MyContext).GetTypeInfo().Assembly.GetName().Name));
return new MyContext(builder.Options);
}
}
but in here i don't want to use hardcode connection string i tried to create appsetting for dynamic connection string :
public class MyContextFactory : IDbContextFactory<ApplicationContext>
{
public MyContext Create()
{
var environmentName =
Environment.GetEnvironmentVariable(
"Hosting:Environment");
var basePath = AppContext.BaseDirectory;
return Create(basePath, environmentName);
}
public MyContext Create(DbContextFactoryOptions options)
{
return Create(
options.ContentRootPath,
options.EnvironmentName);
}
private MyContext Create(string basePath, string environmentName)
{
var configuration = new Configuration();
configuration.AddJsonFile(“config.json”);
var emailAddress = configuration.Get("emailAddress");
var builder = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json", true)
.AddEnvironmentVariables();
var config = builder.Build();
var connstr = config.GetConnectionString("(default)");
if (String.IsNullOrWhiteSpace(connstr) == true)
{
throw new InvalidOperationException(
"Could not find a connection string named '(default)'.");
}
else
{
return Create(connstr);
}
}
private MyContext Create(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
throw new ArgumentException(
$"{nameof(connectionString)} is null or empty.",
nameof(connectionString));
var optionsBuilder =
new DbContextOptionsBuilder<MyContext>();
optionsBuilder.UseSqlServer(connectionString);
return new MyContext(optionsBuilder.Options);
}
}
i stuck in create a instance of this
var configuration = new Configuration();
the entity project doesn't have any reference to Microsoft.Extensions.Configuration I don't know how to add this because of I can't find it. please help me add this reference or suggest me a different way