【问题标题】:EF Core: how do I configure mySql for Linux, and localDB for Windows?EF Core:如何为 Linux 配置 mySql,为 Windows 配置 localDB?
【发布时间】:2018-11-28 01:39:19
【问题描述】:

我有一个使用 LocalDB 的简单 ASP.Net Core/Entity Framework Core 项目。它在 Windows 上编译并运行良好。

我想在 Windows 和 Linux 上构建和运行相同的项目。但是 Linux 不支持 LocalDB。所以我需要将项目配置为使用 mySql,但仅适用于 Linux。

问:如何配置我的项目,以便我可以在 Windows 上使用 LocalDB,而在 Linux 上使用 mySql?

这是我迄今为止尝试过的:

  1. 创建了一个空的 mySql 数据库并授予了一个 mySql 用户的访问权限。

  2. appsettings.json中创建了一个mySql连接字符串:

    {
      "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
    
  3. 更新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));
        }
    

  4. 在 Linux 上:

    1. 已删除所有二进制文件
    2. dotnet restore
    3. dotnet ef migrations add newMigration -c ApplicationDbContext -v

  5. 尝试更新数据库:

    dotnet ef database update

    错误:表“ManageCarDb.__EFMigrationsHistory”不存在

问:鉴于我想要一个用于两种 EF 环境的项目,我是否采取了正确的步骤?

还是我应该采取不同的方法?

【问题讨论】:

    标签: c# asp.net-core entity-framework-core


    【解决方案1】:

    您应该使用 `Pomelo.EntityFrameworkCore.MySql 而不是 Oracle 的 MySql 库。

    我使用Pomelo.EntityFrameworkCore.MySql,它在我的项目中运行良好。

    Oracle 的 MySql 库不像我尝试的那样支持迁移。这个库面临几个问题

    注意:我正在为 Oracle 的网站找到一个讨论此问题的链接

    Error: The method or operation is not implemented. while scaffolding MYSQL Database

    https://bugs.mysql.com/bug.php?id=90368

    【讨论】:

    • 我以为我做错了什么。想象一下我的惊讶这似乎是一个 Oracle/MySql 错误!!!!!!无论如何 - 我卸载了 Oracle 库并安装了 Pomelo.EntityFrameworkCore.MySql ......它就像一个魅力!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2016-11-09
    相关资源
    最近更新 更多