I have a simple ASP.Net Core/Entity Framework Core project that uses LocalDB. It compiles and runs fine on Windows.
I would like to build and run the same project on Windows and Linux. But LocalDB isn't supported on Linux. So I need to configure the project to use mySql instead - but only for Linux.
Q: How do I configure my project so that I can use LocalDB on Windows, but mySql on Linux?
This is what I've tried so far:
Created an empty mySql database and granted access to a mySql user.
Created a mySql connection string in appsettings.json
:
{ "ConnectionStrings": { "DefaultConnection": "Server=(LocalDb)\\\\MSSQLLocalDB;Database=ManageCarDB;Trusted_Connection=True;MultipleActiveResultSets=true", "mySqlConnection": "Server=localhost;port=3306;database=ManageCarDb;uid=dotnetuser;password=dotnetuser" },... <= I've defined two different connection strings: one for LocalDB, one for MySql
Updated Startup.cs
:
public void ConfigureServices(IServiceCollection services) { string env = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); string connectionString; if (!string.IsNullOrEmpty(env) && env.Equals("Linux")) { connectionString = Configuration.GetConnectionString("mySqlConnection"); services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(connectionString)); } else { connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); }
<= Startup will conditionally call either MySql connection string/MySQL data provider, or default/LocalDB
On Linux:
dotnet restore
dotnet ef migrations add newMigration -c ApplicationDbContext -v
<= This all worked OK
Tried to update the database:
dotnet ef database update
<= ERROR: Table 'ManageCarDb.__EFMigrationsHistory' doesn't exist
Q: Given that I'd like one project for both EF environments, am I taking the correct steps?
Or should I taking a different approach?
You should use `Pomelo.EntityFrameworkCore.MySql instead of MySql library from Oracle.
I use Pomelo.EntityFrameworkCore.MySql
and it works well in my project.
MySql library from Oracle is not supporting migration as I did try. This library is facing several issues
Note : I am finding a link that talks about this problem for Oracle's site
Error: The method or operation is not implemented. while scaffolding MYSQL Database
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.