How To connect to mysql database with EntityFramework Core?

0

In the goal to use asp.net core mvc with the mysql database , i have downloaded the specific provider of EF_Core for Mysql.

Then i registred the DbContext service in the startup file:

 services.AddDbContext<NawrasContext>(options=>
               options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

and this is my appsettings.json :

  {
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=s.mysql.db;Database=s2019;Uid=s2019;Pwd=pass;"

  }
}

I have successfully added my first migration , but when i try to update the database , i get this error :

fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
  An error occurred using the connection to database '' on server 's.mysql.db'.
MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
 at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 440 

what i m doing wrong ? why the error is telling me :

An error occurred using the connection to database '' on server 's.mysql.db'. while the name of the database in the connection string is specified ?

mysql
entity-framework-core
connection-string
asked on Stack Overflow Oct 23, 2019 by A.HADDAD • edited Aug 5, 2020 by A.HADDAD

2 Answers

0

Using these steps you can solve the issue

  1. Use a Nugat package named "Pomelo.EntityFrameworkCore.MySql"
  2. Register service to Startup.cs

    services.AddCors();

    services.AddDbContext(options =>options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

  3. Use this connection string in appsettings.json

{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } },

"ConnectionStrings": { "DefaultConnection": "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword; Encrypt=true;" } }

answered on Stack Overflow Oct 25, 2019 by Abdullah Al Mamun Shiham • edited Oct 25, 2019 by Abdullah Al Mamun Shiham
0

I had same issue using mac with MAMP as server for MySQL and the fix for me was to enable Allow network access to MySQL => Only from this Mac and then the server variable in connection string was like this :

"server=/Applications/MAMP/tmp/mysql/mysql.sock;port=8889;user=root;password=MyAwesomePassword;database=MyAwesomeDb;"

so basically try to put the mysql.sock path instead of localhost.

hope this will help someone , thanks .

answered on Stack Overflow Nov 6, 2020 by Softmixt

User contributions licensed under CC BY-SA 3.0