我創建了新的ASP.NET Core項目,其標識爲Individual User
但它沒有創建任何數據庫。我需要手動使用add-migration
update-database
。ASP.NET核心新項目默認情況下不創建數據庫
我記得,過去一切都是自動完成的。不知道這次有什麼不對。
VS2017.3
我創建了新的ASP.NET Core項目,其標識爲Individual User
但它沒有創建任何數據庫。我需要手動使用add-migration
update-database
。ASP.NET核心新項目默認情況下不創建數據庫
我記得,過去一切都是自動完成的。不知道這次有什麼不對。
VS2017.3
根據DOTNET核心的版本,你有,ASP.NET核心可能無法自動當您創建一個新的應用程序爲您創建一個數據庫。
但是,簡單地遷移和更新數據庫應該可以工作。 首先,創建一個語法爲dotnet ef migrations add <MIGRATION_NAME>
的新遷移。像這樣
dotnet ef migrations add InitialMigration
,然後更新,像這樣
dotnet ef database update
數據庫。
這應該可以做到。
您必須觸發它才能自動遷移您的數據庫。與以前版本的ASP.NET MVC不同,this isn't implemented out of the box。
,這是可以實現的一種方式,但是,從你的startup.cs
觸發它,或者某處管道像這樣別人早:
using (var context = new MyDbContext(..))
{
context.Database.Migrate();
}
如果你只想創建一個數據庫模式,你可致電:
//IDbContext context;
context.Database.EnsureCreated();
EnsureCreated
完全繞過遷移併爲您創建模式,但不能將其與遷移混合使用。EnsureCreated
專爲測試或快速原型設計而設計,您可以隨時丟棄和重新創建數據庫。如果您正在使用遷移並希望將它們自動應用於應用程序啓動,則可以使用context.Database.Migrate()
代替。
[這打破了遷移](https://stackoverflow.com/questions/38238043/how-and-where-to-call-database-ensurecreated-and-database-migrate)。 – CodeCaster
要啓用自動遷移,你需要把它添加到您的配置:
public class MigrateDBConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<DbContext>
{
public MigrateDBConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
}
要啓用自動更新到你的數據庫,你需要添加Database.SetInitializer(...)在OnModelCreating()方法在您的上下文中:
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");
}
}
}
我有一種感覺,這個答案是Asp.NET MVC,而不是ASP.NET Core?我不認爲ASP.NET Core具有'AutomaticMigrationsEnabled' – Luke
分享您的代碼以獲得更好的幫助。@Wakka Sakka –
[EntityFramework Core自動遷移]的可能重複(https://stackoverflow.com/questions/39526595/entityframework-core-automatic-migrations) – CodeCaster
沒有額外的代碼。我只是創建新的aspnet核心1.1項目有一個遷移文件夾,但在服務器資源管理器是沒有任何數據庫。我必須'手動更新數據庫' –