ASP.NET Core在类中获取WebRootPath以种子数据库

时间:2016-11-17 18:14:07

标签: entity-framework asp.net-core-mvc

使用ASP.NET Core MVCEntity Framework 6,我希望使用我放在wwwroot\data

中的CSV文件中的数据为我的代码优先数据库播种

我正在尝试访问执行种子的类中的WebRootPath值但无法使其工作。我知道解决方案是基于依赖注入,虽然对于ASP.NET核心和依赖注入是一个非常新的东西我还没有这个工作。

Startup.cs - 标准代码,通过另一个SO问题找到DbContext设置。

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add DbContext
        services.AddScoped(p =>
        {
            var connectionString = Configuration["Data:ProjectDbContext:ConnectionString"];
            return new ProjectDbContext(connectionString);
        });

        // Add framework services.
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

ProjectDbContext.cs

[DbConfigurationType(typeof(DbConfig))]
public class ProjectDbContext : DbContext
{
    static ProjectDbContext ()
    {
        Database.SetInitializer(new ProjectInitializer());
    }

    public ProjectDbContext (string connectionName) : base(connectionName)
    {

    }

    public DbSet<SomeEntity> SomeEntity{ get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        base.OnModelCreating(modelBuilder);
    }
}

ProjectInitializer.cs

public class ProjectInitializer : DropCreateDatabaseAlways<ProjectDbContext>
{
    private readonly IHostingEnvironment _appEnvironment;

    public ProjectInitializer(IHostingEnvironment appEnvironment)
    {
        _appEnvironment = appEnvironment;
    }

    public override void InitializeDatabase(ProjectDbContext context)
    {
        base.InitializeDatabase(context);
    }

    protected override void Seed(ProjectDbContext db)
    {
        string dataPath = Path.Combine(_appEnvironment.WebRootPath, "data");
        string contracts = Path.Combine(dataPath, "Data.csv");

        // Parse file, create objects

        db.SaveChanges();
    }
}

1 个答案:

答案 0 :(得分:0)

我已经按照以下方式更改了课程,虽然我不确定它是完全正确的但是有效:

<强> Startup.cs

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
    HostingEnvironment = env;
}

public IHostingEnvironment HostingEnvironment { get; }
public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add DbContext
    services.AddScoped(p =>
    {
        var connectionString = Configuration["Data:ProjectDbContext:ConnectionString"];
        return new ProjectDbContext(connectionString, HostingEnvironment);
    });

    // Add framework services.
    services.AddMvc();
}

<强> ProjectDbContext.cs

[DbConfigurationType(typeof(DbConfig))]
public class ProjectDbContext : DbContext
{
    public ProjectDbContext(string connectionName, IHostingEnvironment appEnvironment) : base(connectionName)
    {
        Database.SetInitializer(new ProjectInitializer(appEnvironment));
    }

    public DbSet<SomeEntity> SomeEntity { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        base.OnModelCreating(modelBuilder);
    }
}

<强> ProjectInitializer.cs

private readonly IHostingEnvironment _appEnvironment;

public ProjectInitializer(IHostingEnvironment appEnvironment)
{
    _appEnvironment = appEnvironment;
}

public override void InitializeDatabase(ProjectDbContext context)
{
    base.InitializeDatabase(context);
}

protected override void Seed(ProjectDbContext db)
{
    string dataPath = Path.Combine(_appEnvironment.WebRootPath, "data");
    string contracts = Path.Combine(dataPath, "Data.csv");

    // Parse file, create objects

    db.SaveChanges();
}