0

I'm trying to connect to my MySql Workbench database in ASP.NET Core. I'm following a youtube guide where I'm told to write some stuff in the Package Manager Console:

Add-Migration "Initial-Create"

And then:

Update-Database

Now when I run the second command I get this:

Build started...
Build succeeded.
System.ArgumentException: Keyword not supported: 'port'.
   at Microsoft.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms, Boolean firstKey)
   at Microsoft.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
   at Microsoft.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
   at Microsoft.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
   at Microsoft.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
   at Microsoft.Data.SqlClient.SqlConnection..ctor(String connectionString)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.CreateDbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Keyword not supported: 'port'.

My connectionstring looks like this:

"AuthDBContextConnection": "Server=localhost;Port=xxxx;Database=xxxx;User ID = xxx;Password=xxxx;Pooling=false;SslMode=none;convert zero datetime=True;Trusted_Connection=True;MultipleActiveResultSets=true"

I've tried googling it and checking stackoverflow for similar questions but can't find the solution. Every solution I've come across I need to change something in the web.config file. The problem is I don't even have a web.config file in my project.

Any ideas?

Thank you!

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
leo
  • 91
  • 1
  • 10
  • https://www.connectionstrings.com/mysql/ – Camilo Terevinto Nov 03 '21 at 16:48
  • @camilo I’m not having problems writing the connection string. I’m having problems importing the database. The string should be correct since I’ve tried using it directly in my controller and it works. – leo Nov 03 '21 at 16:52
  • The following may be helpful: https://stackoverflow.com/questions/3715925/localhost-vs-127-0-0-1-in-mysql-connect – Tu deschizi eu inchid Nov 03 '21 at 16:54
  • @Camilo I’ve only used it in that string. Weird. I only tried it directly in the controller and then removed it. – leo Nov 03 '21 at 16:55
  • Nevermind, that wasn't the problem. `Microsoft.EntityFrameworkCore.SqlServer` -> SQL Server -> you're using MySQL -> use the correct extension methods – Camilo Terevinto Nov 03 '21 at 16:59
  • @user9938 thanks. Will check it out. https://stackoverflow.com/questions/45217166/c-sharp-entity-framework-keyword-not-supported-port This is the thread that I’ve tried to follow, mainly Ivan Stoev’s reply, but none of them worked. The difference here is that the person in that thread has a Web.config-file, while I don’t – leo Nov 03 '21 at 17:01
  • @Camilo I’ve tried following the steps in the thread I posted in the previous comment. The thing is that many of these changes are made in the web.config file. I tried creating one and changing the defaultconnectionfactory, the dbconfigurationtypr etc and I’m not getting it to work. – leo Nov 03 '21 at 17:10
  • @CamiloTerevinto how did you resolve this issue please? can you expand on your earlier comment a little please? Thank you. – RichJohnstone Dec 03 '21 at 12:01

2 Answers2

1

It is supposed to be done like this:

"AuthDBContextConnection": "Server=localhost,YourPortHere;Database=xxxx;User ID = xxx;Password=xxxx;Pooling=false;SslMode=none;convert zero datetime=True;Trusted_Connection=True;MultipleActiveResultSets=true"
XKZ
  • 126
  • 7
0

The error was similar while working with ASP.net core and Database. default database Provider with the ASP.net core is the SQL Server but, in case you are using a different provider, you will find this error.

looking like you are using MySQL DB in your project. update your code like below in your startup.cs file.

public void ConfigureServices(IServiceCollection services)
{

   ....

  services.AddDbContext<YourDbContextName>(options =>
                options.UseMySql(
                    Configuration.GetConnectionString("AuthDBContextConnection")));
}

Don't forget to install NuGet package MySql.Data.EntityFramework Hope it will resolve your issue.

UPDATE

Your Need these NuGet packages, please install these. it will resolve your issue.

using Microsoft.EntityFrameworkCore;
using MySQL.Data.EntityFrameworkCore.Extensions;
using MySql.Data.EntityFrameworkCore

AGAIN UPDATE

Install these:-

Microsoft.EntityFrameworkCore (v5.0.0 – the latest stable version)
Microsoft.EntityFrameworkCore.Tools (v5.0.0 – the latest stable version)
Pomelo.EntityFrameworkCore.MySql (version 5.0.0-alpha.2)

Your connectionstring look like this:-

"ConnectionStrings": {  
    "DefaultConnection": "server=localhost; port=3306; database=test; user=root; password=Wxp@Mysql; Persist Security Info=False; Connect Timeout=300"  
  }  

And Update your startup.csfile:-

public void ConfigureServices(IServiceCollection services)  
        {  
            string mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection");  
            services.AddDbContextPool<MyDBContext>(options => options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));  
  
            services.AddControllers();  
        }  

Now it will resolve your issue.

Pritom Sarkar
  • 2,154
  • 3
  • 11
  • 26
  • It's not working. I added the text and installed MySql.Data.EntityFramework. But "UseMySql" has an error. It says: "CS1061: 'DbContextOptionsBuilder' does not contain a definition for 'UseMySql' and no accessible extension method 'UseMySql' accepting a first argument of typ 'DbContextOptionsBuilder' could be found (are you missing a using directive or an assembly reference?) I have no idea what to write in "using". I've tried "using MySql.Data.EntityFrameWork" but same thing. – leo Nov 04 '21 at 21:21
  • @Tarik Gen When I tried you solution I get this: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - No connection could be made because the target machine actively refused it.)". Now the connection I'm trying to make is to my school's server via a tunnel. Could it by my school is blocking the connection? – leo Nov 04 '21 at 21:45
  • I can't find the the nuget package "MySQL.Data.EntityFrameworkCore.Extensions". And I installed the MySql.DataEntityFrameworkCore. It is deprecated though. – leo Nov 05 '21 at 11:54
  • @leo Does the error still exist same? – Pritom Sarkar Nov 05 '21 at 11:57
  • no, I get "Build Failed" now. But I can't find where the code is wrong. – leo Nov 05 '21 at 11:59
  • @leo check where the code is in error in the error portion. – Pritom Sarkar Nov 05 '21 at 12:02
  • @leo I updated my answer please check.now definitely it will resolve your issue. – Pritom Sarkar Nov 05 '21 at 12:11
  • I had done something wrong. I get the "Exception has been thrown by the target of an invocation." though after fixing it. Can we chat so I can explain step by step what I'm trying to do? – leo Nov 05 '21 at 12:18
  • 1
    ok will try the latest update. I'll get back to you. – leo Nov 05 '21 at 12:19
  • @leo I actually don't know where you are stuck. i will suggest you use my recent update answer.it will work. – Pritom Sarkar Nov 05 '21 at 12:20
  • I tried the latest update and I get "Exception has been thrown by the target of an invocation.". Here is step by step what I'm doing: Create Project -> ASP.NET Core Web App (Model-View-Controller) -> Add Scaffolded Item -> Identity -> AppUser -> I insert the data FirstName and LastName -> Add All Nuget packages you said -> Startup.cs -> I add the code you gave me -> appsettings.json -> Change the connectionstring -> Package Manager Console -> Add-Migration "Initial-Create" and HERE is where I get the error. – leo Nov 05 '21 at 12:30
  • what exactly you found error please let me know.by the way,you have to correctly use your mysql port user and password correctly in connection string. – Pritom Sarkar Nov 05 '21 at 12:36
  • Here is the error. https://pastebin.com/T673Kt4v The mysql port, username and password are correct. – leo Nov 05 '21 at 12:39
  • @leo what .net core version used in your project? – Pritom Sarkar Nov 05 '21 at 12:47
  • @leo I will suggest you install all your NuGet packages especially ```Microsoft.EntityFrameworkCore``` and ```Microsoft.EntityFrameworkCore.Tool``` similar to your .net core version.for example:- if your .net version is 2.2 then your nuget package will be 2.1 or 2.2 something.it will resolve your issue. – Pritom Sarkar Nov 05 '21 at 12:51
  • I was using 3.1. I changed to 5 now and now I get this error haha: https://pastebin.com/cs4rMfeL Error after error :( – leo Nov 05 '21 at 12:55
  • @leo no need to change .net core version in your project. you used 3.1 that's ok.you have to just downgrade nuget package version. – Pritom Sarkar Nov 05 '21 at 12:57
  • it's very problematic to migrate the .net core version.just downgrade nuget package which i already mentioned. – Pritom Sarkar Nov 05 '21 at 12:59
  • it's a fresh project. I mean this is the first thing I'm trying to implement, so it's not a big deal. So if it works with 5.0 I will just continue the project using 5.0 – leo Nov 05 '21 at 12:59
  • @leo can you give me your dbcontext class and appsetting file? – Pritom Sarkar Nov 05 '21 at 13:06
  • https://pastebin.com/p3fmu5JX – leo Nov 05 '21 at 13:09
  • @leo just inherit Dbcontext like:- ```public class AuthDBContext : DbContext ``` but still could not give me your appsettings file. and your AppUser model look like:- ```public class AppUser:IdentityUser ``` hope now works well. – Pritom Sarkar Nov 05 '21 at 13:15
  • I'm still getting this error: https://pastebin.com/cs4rMfeL This is my AppUser model: https://pastebin.com/z7VuZvHG , this is my AuthDbContext: https://pastebin.com/KhRELB2f and this is my appsettings: https://pastebin.com/3u1wiFvz – leo Nov 05 '21 at 13:26
  • ```"ConnectionStrings": { "DefaultConnection": "server=localhost; port=3306; database=test; user=root; password=Wxp@Mysql; Persist Security Info=False; Connect Timeout=300" }``` use this connection string exact same just update port,database and user – Pritom Sarkar Nov 05 '21 at 13:40
  • also update this your startup file exact same:-```string mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection"); ``` – Pritom Sarkar Nov 05 '21 at 13:42
  • I still get the same. I'm starting to think it's a problem with my school's server and not the setup. I'm connected to the schools server using a ssh-tunnel. – leo Nov 05 '21 at 13:43
  • @leo oh my god!! I thought you are trying locally. – Pritom Sarkar Nov 05 '21 at 13:45
  • I am connecting to it locally. Via localhost. I'm using exactly these values to connect to the database in MySQL. I can get it to work using the connection string individually in the controller. But when I try to connect using this method it doesn't work. So the connectionstring should be correct. – leo Nov 05 '21 at 13:47
  • @leo bro. my updated all answer is correct and will work perfectly I know. I was suffered because of your school server. – Pritom Sarkar Nov 05 '21 at 13:47
  • @leo also check your startup file,the name is correct or not. – Pritom Sarkar Nov 05 '21 at 13:50
  • Sorry about that. Didn't mean to mislead, but I did write it in a previous comment that I'm connecting to my school's server. I appreciate all your help! Where did you update? – leo Nov 05 '21 at 13:51
  • if not work,i will connect your pc via team viewer software. – Pritom Sarkar Nov 05 '21 at 13:51
  • @leo check your startup file ,name is ok or not. if still not work,i will connect your pc via team viewer software. – Pritom Sarkar Nov 05 '21 at 13:52
  • I'm not seeing any updates anywhere. Name should be correct – leo Nov 05 '21 at 13:54
  • @leo check your startup file this line:- ```string mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection");``` is this exact same or not. – Pritom Sarkar Nov 05 '21 at 13:55
  • yes it is exact same. – leo Nov 05 '21 at 13:56
  • @leo ok,i will connect your pc via team viewer. have you ever installed team viewer software in your pc? – Pritom Sarkar Nov 05 '21 at 13:57
  • Yeah I have it, I know how to use it. But I'll give you the details in PM. Can you pm me? – leo Nov 05 '21 at 13:58
  • what do you mean PM? please briefly explain – Pritom Sarkar Nov 05 '21 at 13:59
  • Private message – leo Nov 05 '21 at 13:59
  • but I know stackoverflow have no system to give personal message. – Pritom Sarkar Nov 05 '21 at 14:00
  • @leoI actually did not use discord before.ok i will use discord no problem. but the problem is due to my final exam, I will connect your pc and add your discord the next day at this same time.see you then. – Pritom Sarkar Nov 05 '21 at 14:04
  • oh. The reason for that is I don't want to give my teamviewer connecting details here publically. We don't have to use discord. I just wanna be able to PM you the teamviewer details. If you know somewhere we can chat privately then let me know. Yes it's no stress. Good luck at your final exam! – leo Nov 05 '21 at 14:06
  • @leo you already remove your discord code and i not copied yet. next day i will connect your pc in this same time.please give me your discord id again. – Pritom Sarkar Nov 05 '21 at 14:08
  • Ok leo,now you can remove it.see you then. – Pritom Sarkar Nov 05 '21 at 14:11
  • yes. And again good luck on the exam! Hope you ace it. See you. – leo Nov 05 '21 at 14:12