我被告知以下是在asp.net core 2.0中播种数据库的正确方法,即必须在program.cs中完成。
我想从文件系统中的CSV文件中播种数据库。但是,我无法想象在Main函数中访问内容根或Web根等。
//Program. cs
public class Program
{
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<EventContext>();
// => How can I get the webrootpath here to pass to the seed function?
// => I cannot figure how to access the HostingEnvironment
DbInitialize.Seed(context);
}
catch (Exception ex)
{
....
}
}
host.Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
答案 0 :(得分:0)
不确定您是否已获得答案或找到解决方案,但不确定我们在项目中所做的事情。
public class SeedData
{
public static void Seed(IServiceProvider serviceProvider)
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var env = serviceScope.ServiceProvider.GetRequiredService<IHostingEnvironment>();
var webRoot = env.WebRootPath;
}//end using scope
}// end class
和用法
public class Program
{
public static void Main(string[] args)
{
var isSeed = args.Contains("/seed");
if (isSeed)
{
args = args.Except(new[] { "/seed" }).ToArray();
}
var host = BuildWebHost(args);
if (isSeed)
{
SeedData.EnsureSeeded(host.Services);
}
host.Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}