asp.net core MySQL 數據遷移

開發項目過程中遇到這個問題,找了很多方法都沒用,然後看到下面作爲的文章完美解決問題

*********   原始博文來之 https://blog.csdn.net/u011010407/article/details/81034180

使用命令 dotnet ef migrations add InitialCreate遷移時出現問題:(UserRoleIdentityDbContext是項目中數據庫上下文的自定義派生類)

 

 

 解決方案:

1.安裝MySQL數據包:Pomelo.EntityFrameworkCore.MySql   (使用官方的MySQL包會出錯)

2. 然後在編寫數據庫上下文的cs文件添加下面的一個class以内容(UserRoleIdentityDbContext是自己的數據庫上下文派生類)

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<UserRoleIdentityDbContext>
{

public UserRoleIdentityDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();

var connectionString = configuration.GetConnectionString("mysql");

var builder = new DbContextOptionsBuilder<UserRoleIdentityDbContext>();
builder.UseMySql(connectionString,
mysqlOptions =>
{

mysqlOptions.ServerVersion(new Version(5, 7, 31), ServerType.MySql);
}
);

return new UserRoleIdentityDbContext(builder.Options);
}
}

3. 在上面代碼文件的當前目錄下面執行命令行   ( ../tz.web是工程文件目錄)

dotnet ef migrations add [<The name of the migration>] -s ../tz.web

dotnet ef database update -s ../tz.web

 

posted @ 2020-07-29 15:26  凌青语  阅读(61)  评论(0编辑  收藏  举报