Asp.net 如何以及在何处调用Database.com和Database.Migrate?

Asp.net 如何以及在何处调用Database.com和Database.Migrate?,asp.net,asp.net-mvc,entity-framework,entity-framework-core,Asp.net,Asp.net Mvc,Entity Framework,Entity Framework Core,我有一个ASP.NET MVC 6应用程序,需要调用数据库。请重新创建和数据库。迁移方法 但是我应该把他们叫到哪里去呢?正如你应该从罗文·米勒那里读到的前言: 重新创建完全绕过迁移,只创建 对于您来说,您不能将此与迁移混合使用重新创建是 专为测试或快速原型设计,您可以 每次删除并重新创建数据库。如果您正在使用 并希望在应用程序启动时自动应用迁移, 然后可以使用context.Database.Migrate() 根据答案,您需要添加Globals.EnsureDatabaseCreated()将

我有一个ASP.NET MVC 6应用程序,需要调用
数据库。请重新创建
数据库。迁移
方法


但是我应该把他们叫到哪里去呢?

正如你应该从罗文·米勒那里读到的前言:

<代码>重新创建
完全绕过迁移,只创建 对于您来说,您不能将此与迁移混合使用<代码>重新创建
是 专为测试或快速原型设计,您可以 每次删除并重新创建数据库。如果您正在使用 并希望在应用程序启动时自动应用迁移, 然后可以使用
context.Database.Migrate()

根据答案,您需要添加
Globals.EnsureDatabaseCreated()将其发送到
Startup.cs

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();
    }

要使用
context.Database.Migrate()
请参阅或。

我认为这是一个重要的问题,应该得到很好的回答

什么是数据库。请重新创建?

context.Database.EnsureCreated()
是新的EF核心方法,可确保上下文的数据库存在。如果存在,则不采取任何行动。如果它不存在,则创建数据库及其所有模式,并确保它与此上下文的模型兼容

注: 此方法不使用迁移来创建数据库。此外,以后无法使用迁移更新创建的数据库。如果您以关系数据库为目标并使用迁移,则可以使用
DbContext.database.Migrate()
方法来确保创建数据库并应用所有迁移

我们是如何使用EF 6做到这一点的?

context.Database.EnsureCreated()
相当于下面列出的EF 6方法:

  • 包管理器控制台:

    启用迁移—启用自动迁移。添加迁移/更新数据库

  • 从代码:

    Database.SetInitializer CreateDatabaseIfNotExists

  • 使用DBMigOptionsConfiguration并设置AutomaticMigOptionsEnabled=true

    什么是数据库。迁移?

    将上下文的所有挂起迁移应用于数据库。如果数据库不存在,将创建该数据库

    我们是如何使用EF 6做到这一点的?

    context.Database.Migrate()
    相当于下面列出的EF 6方法:

  • 包管理器控制台:

    更新数据库-TargetMigration

  • 使用自定义DBMigOptionsConfiguration:

    AutomaticMiggerationsEnabled=假;或者使用DbMigrator

  • 结论

    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();
    }
    

    如果您使用的是迁移,则存在
    context.Database.Migrate()
    。如果您不想要迁移,只想要一个快速的数据库(通常用于测试),那么就使用context.database.EnsureCreated()/EnsureDeleted()。

    根据James p和Bassam Alugili提供的信息,我最后要做的是将这些代码行添加到
    Startup
    类(Startup.cs)中的
    Configure
    方法中:

    使用(变量范围=
    app.ApplicationServices.CreateScope())
    使用(var context=scope.ServiceProvider.GetService())
    Migrate();
    
    此外,如果在上下文的构造函数中调用此函数,您可能会看到性能下降。。。将重新创建的
    移动到setup.cs实用程序后,我注意到响应时间有了很大的改进


    注意:我正在使用EFC和UWP。

    通常,
    DbContext
    将添加到
    Startup.ConfigureServices()中的依赖项注入容器中,如下所示:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration 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 to the injection container
            services.AddDbContext<MyDbContext>(options =>
                    options.UseSqlServer(
                        this.Configuration.GetConnectionString("DefaultConnection")));
        }
    }
    

    请记住,正如EF核心文档中所引用的那样,
    Database.EnsureCreated()
    Database.Migrate()
    不能一起使用,因为可以确保将现有的迁移应用于数据库,而数据库是在需要时创建的。另一个只是确保数据库存在,如果不存在,则创建一个反映您的
    DbContext
    ,包括在上下文中通过Fluent API进行的任何种子设定。

    你好,James,谢谢您的回答!,在我的启动方法中,我没有访问可变名称Globals的权限,我如何才能访问它?同样,没有看到
    Globals
    。这看起来像是一种非标准的方式试图撬开这条信息。据我所知,标准的方式是DbContext是在Startup.ConfigureServices中创建的,但是通过某种间接方法创建的。您可以在那里或在启动时重新捕获。使用app.ApplicationServices.GetRequiredService进行配置。我想。你好,巴萨姆·阿鲁吉利,谢谢你的回答!在我的项目中,我使用迁移,我不知道不能同时使用这两种方法。uw下面是一个如何调用它的示例!我想,
    Database.Migrate()
    创建迁移(如果需要),然后基于它更新数据库。与EF6中的自动迁移类似。但我错了。它仅在数据库上应用现有迁移(如果有)。据我所知,数据库。迁移使用的数据库信誉与应用程序在数据库中执行插入/查询等操作时使用的数据库信誉相同。我们是否希望这些操作由具有创建/删除权限的用户执行?有没有一种方法可以让Database.Migrate()使用其他信用(具有创建/删除权限)?您刚刚救了我,使我免于将来的灾难。你可能不想使用这两种方法。MS docs在使用Migrate()时这样说:“虽然它非常适合使用本地数据库的应用程序,但大多数应用程序都需要更健壮的部署策略,如生成SQL脚本。”这正是我所寻找的。大多数示例使用.NETCore或Web,我使用的是带有.NET4.6的Windows窗体应用程序。数据库
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration 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 to the injection container
            services.AddDbContext<MyDbContext>(options =>
                    options.UseSqlServer(
                        this.Configuration.GetConnectionString("DefaultConnection")));
        }
    
        public static void Configure(IApplicationBuilder app, IWebHostEnvironment env, MyDbContext context)
        {
            if (env.IsDevelopment())
            {
                context.Database.EnsureCreated();
                //context.Database.Migrate();
            }
        }
    }