ASP.NET Core新项目默认情况下不创建数据库

时间:2017-08-15 08:33:03

标签: asp.net-mvc asp.net-core visual-studio-2017 entity-framework-core

我使用Identity Individual User创建了新的ASP.NET Core项目,但它没有创建任何数据库。

我必须手动使用add-migration update-database

我记得,过去,一切都是自动完成的。不知道这次出了什么问题。

VS2017.3

4 个答案:

答案 0 :(得分:1)

您必须触发它才能自动迁移数据库。与以前版本的ASP.NET MVC不同,this isn't implemented out of the box

然而,可以实现这一目标的方法是从您的startup.cs或其他早期的其他地方触发它,如下所示:

using (var context = new MyDbContext(..))
{
    context.Database.Migrate();
}

答案 1 :(得分:1)

如果您只想创建数据库模式,可以调用:

<?php
$name       = @trim(stripslashes($_POST['name'])); 
$from       = @trim(stripslashes($_POST['email'])); 
$subject    = @trim(stripslashes($_POST['subject'])); 
$message    = @trim(stripslashes($_POST['message'])); 
$to         = '<myemail@domain.com>';//replace with your email
$echo       =("Thank you for contacting us!");

$headers   = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

mail($to, $subject, $message, $headers);

die;

But note, that

  

//IDbContext context; context.Database.EnsureCreated(); 完全绕过迁移,只是为您创建架构,您不能将其与迁移混合在一起。 EnsureCreated用于测试或快速原型设计,您可以在每次删除和重新创建数据库时使用。如果您正在使用迁移并希望在应用启动时自动应用迁移,则可以使用EnsureCreated代替。

答案 2 :(得分:0)

要启用自动迁移,您需要将其添加到配置中:

public class MigrateDBConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<DbContext>
{
public MigrateDBConfiguration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}
}

要启用对数据库的自动更新,您需要在上下文的OnModelCreating()方法中添加Database.SetInitializer(...):

public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, MigrateDBConfiguration>());
}

...
}

您还可以使用Fluent migration自动进行数据库更新和迁移。
以下是Here中如何使用它的示例:

using FluentMigrator;
namespace DatabaseMigration.Migrations
{
    [Migration(1)]
    public class M0001_CreateMemberTable:Migration
    {
        public override void Up()
        {
            Create.Table("Member")
                .WithColumn("MemberId").AsInt32().PrimaryKey().Identity()
                .WithColumn("Name").AsString(50)
                .WithColumn("Address").AsString()
                .WithColumn("MobileNo").AsString(10);
        }

        public override void Down()
        {
            Delete.Table("Member");
        }
    }
}

答案 3 :(得分:0)

根据您拥有的dotnet核心版本,ASP.NET核心可能无法在您创建新应用时自动为您创建数据库。

但是,只需迁移和更新数据库即可。 首先,使用语法dotnet ef migrations add <MIGRATION_NAME>创建新的迁移。像这样

dotnet ef migrations add InitialMigration

然后像这样更新数据库

dotnet ef database update

这应该可以解决问题。

相关问题