56 lines
1.9 KiB
C#
56 lines
1.9 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Design;
|
|
|
|
namespace Microsoft.SelfService.Portal.Core.API.Context
|
|
{
|
|
public class DataContextFactory : IDesignTimeDbContextFactory<DataContext>
|
|
{
|
|
public DataContext CreateDbContext(string[] args)
|
|
{
|
|
var basePath = ResolveBasePath();
|
|
var configuration = new ConfigurationBuilder()
|
|
.SetBasePath(basePath)
|
|
.AddJsonFile("appsettings.json", optional: false)
|
|
.AddJsonFile("appsettings.Development.json", optional: true)
|
|
.AddEnvironmentVariables()
|
|
.Build();
|
|
|
|
var connectionString = configuration.GetConnectionString("Context")
|
|
?? throw new InvalidOperationException("Connection string 'Context' not found.");
|
|
|
|
var optionsBuilder = new DbContextOptionsBuilder<DataContext>();
|
|
optionsBuilder.UseSqlServer(connectionString);
|
|
|
|
return new DataContext(optionsBuilder.Options);
|
|
}
|
|
|
|
private static string ResolveBasePath()
|
|
{
|
|
var currentDirectory = Directory.GetCurrentDirectory();
|
|
var projectDirectory = Path.Combine(
|
|
currentDirectory,
|
|
".Net",
|
|
"Microsoft.SelfService.Portal.Core.API");
|
|
|
|
if (File.Exists(Path.Combine(currentDirectory, "appsettings.json")))
|
|
{
|
|
return currentDirectory;
|
|
}
|
|
|
|
if (File.Exists(Path.Combine(projectDirectory, "appsettings.json")))
|
|
{
|
|
return projectDirectory;
|
|
}
|
|
|
|
var assemblyDirectory = AppContext.BaseDirectory;
|
|
if (File.Exists(Path.Combine(assemblyDirectory, "appsettings.json")))
|
|
{
|
|
return assemblyDirectory;
|
|
}
|
|
|
|
return currentDirectory;
|
|
}
|
|
}
|
|
}
|
|
|