带有Identity组件的Asp.net MVC EF。
我需要从目录中检索所有文件,并在应用程序启动时将它们添加到数据库中。例如,我无法将它放在HomeController中,因为每次有人访问该页面时都会这样。
这是我想要运行的代码。
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Images"));
var folders = di.GetDirectories().ToList().Select(d => d.Name);
var files = di.GetFiles();
foreach (var file in files)
{
var image = new Image{ name = file.ToString() };
db.Images.Add(image);
}
我试过把它放在这里
public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
//Here
protected override void Seed(ApplicationDbContext context)
{
//Here
}
}
但是我得不到用户Server.MapPath
我应该把代码放在哪里?
答案 0 :(得分:0)
您应该使用此http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath.aspx而不是Server.MapPath将此代码添加到Global.ascx.cs文件中的Application_Start()方法。
它完全按照它在锡上说的那样:)
答案 1 :(得分:0)
//Put it in the Global.asax.cs file
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ScanFiles();
}
private void ScanFiles()
{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Images"));
var folders = di.GetDirectories().ToList().Select(d => d.Name);
var files = di.GetFiles();
foreach (var file in files)
{
var image = new Image { name = file.ToString() };
db.Images.Add(image);
//Hopefully, you have called SaveChanges() , because it is not seen here but hopefully you have called it in the Add method
}
}