Database.EnsureCreated EF 7 ASP.NET 5 MVC 6上的堆栈溢出异常

时间:2016-03-10 10:09:50

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

我在Application Start创建数据库时遇到错误,而完全相同的代码在所有其他项目中完全正常。

Startup.cs中的启动功能

public Startup(IHostingEnvironment env)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();

    if (env.IsDevelopment())
    {
        // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
    }
    Configuration = builder.Build();
    Globals.Configuration = Configuration;
    Globals.HostingEnvironment = env;
    Globals.EnsureDatabaseCreated();
}

Globals.EnsureDatabaseCreated()

public static void EnsureDatabaseCreated()
    {
        var optionsBuilder = new DbContextOptionsBuilder();
        if (HostingEnvironment.IsDevelopment()) optionsBuilder.UseSqlServer(Configuration["Data:dev:DataContext"]);
        else if (HostingEnvironment.IsStaging()) optionsBuilder.UseSqlServer(Configuration["Data:staging:DataContext"]);
        else if (HostingEnvironment.IsProduction()) optionsBuilder.UseSqlServer(Configuration["Data:live:DataContext"]);
        var context = new ApplicationContext(optionsBuilder.Options);
        context.Database.EnsureCreated();

        optionsBuilder = new DbContextOptionsBuilder();
        if (HostingEnvironment.IsDevelopment()) optionsBuilder.UseSqlServer(Configuration["Data:dev:TransientContext"]);
        else if (HostingEnvironment.IsStaging()) optionsBuilder.UseSqlServer(Configuration["Data:staging:TransientContext"]);
        else if (HostingEnvironment.IsProduction()) optionsBuilder.UseSqlServer(Configuration["Data:live:TransientContext"]);
        new TransientContext(optionsBuilder.Options).Database.EnsureCreated();
    }

ApplicationContext.cs

public class ApplicationContext : DbContext
{
    public DbSet<Models.Security.User> Logins { get; set; }
    public DbSet<Models.Security.Session> Sessions { get; set; }
    public DbSet<Models.Security.Verification> VerificationTokens { get; set; }

    public DbSet<Models.CRM.User> Users { get; set; }
    public DbSet<Models.CRM.Organization> Merchants { get; set; }
    public DbSet<Models.CRM.LinkedAddress> Shops { get; set; }
    public DbSet<Models.CRM.ContactDetail> ContactDetails { get; set; }
    public DbSet<Models.CRM.Location> Locations { get; set; }

    public ApplicationContext(DbContextOptions options) : base(options)
    {
    }
}

错误截图

enter image description here

1 个答案:

答案 0 :(得分:0)

在等待了两天的答案之后,不幸的是我最终创建了一个新项目并在那里复制代码并且工作正常。看起来像配置问题。

注意:由于我没有收到任何答案,我将此标记为正确答案。如果用户将来和他们分享他们的观点,我会很乐意标记他们的答案,如果它为未来的读者增加了一些价值。