Connecting database to .net core MVC project - c#

It is my first time using .NET core 2.2 and MySQL workbench ,
I am trying to build a very basic website.
I followed the following Microsoft tutorial
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-2.2&tabs=visual-studio
After I added a Scaffolded item,I followed the instructions and opened the NuGet package manager and executed these commands in the cli:
Add-Migration Initial
Update-Database
The Update-Database command raised the following error :
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: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I am working with a Bluehost (Shared Host) server, I modified the permissions so I could connect remotely to the database (and indeed I am connected through MySQL workbench)
I tried changing the ConnectionString to the following:
"ConnectionStrings":
{
"Piano3Context": "Server=162.241.*.*;Database=PianoDB;User Id=omyUsrName;password=myPass;Trusted_Connection=True;MultipleActiveResultSets=true;"
}
and yet I receive the same error.
If any other code will help please note and I will post.

The tutorial you mentioned is using and SQL-Server. For connecting to a MySql server you need a different database provider. You can install the Pomelo.EntityFrameworkCore.MySql nuget package for Mysql. See the providers page in the microsoft docs.
After that you need to change the options.UseSqlServer from the tutorial to options.UseMySql as described on the mysql providers project page.

In addition, this is how to set the options for MySQL, you can move the config string to the Configuration and use the GetConnectionString method.
services.AddDbContextPool<MvcMovieContext>(
options => options.UseMySql("Server=localhost;Database=ef;User=root;Password=123456;",
mySqlOptions =>
{
mySqlOptions.ServerVersion(new Version(5, 7, 17), ServerType.MySql); // replace with your Server Version and Type
}
));

I was beaten to it by #philipp-grathwohl you need to use MySql and configure that in your startup like his answer says.
You could use this command instead which Scaffolds the DBContext and Generates the EF models and Context in one command after you have changed the startup and added the nuget package Pomelo.EntityFrameworkCore.MySql:
Scaffold-DbContext "Server=<ip>;Initial Catalog=PianoDB;Persist Security Info=False;User ID=<username>;Password=<password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -context Piano3Context -force
Do let me know if this last command spits out any errors.

Related

EF Core understanding migrations

I encountered some weird behaviour with EF Core 3.1 that made me wondering what is actually happening. So hopefully someone can explain this to me in all fine details.
Scenario
Let's say you have two projects. Project A (main) and project B (side-project). For both projects you can add/remove migrations, as project A is set-up to get all pending migrations from project B on start-up and execute them.
When executingdotnet ef migrations add Test -c AppDbContext -o DbContexts/Migrations/AppDb on project A and after completion (BEFORE even applying it to the DB) execute dotnet ef migrations remove -c AppDbContext, everything works as expected and the migration gets removed.
For project B on the otherhand after succesfully executing the add command, the moment that I try to execute the remove command (also BEFORE even applying it to the DB), I get the following error:
Microsoft.Data.SqlClient.SqlException (0x80131904): 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: Named Pipes Provider, error: 40 -
Could not open a connection to SQL Server)
So I took the error message as an advice and started to follow this guide to allow remote access to the database. After the guide, the remove command on project B was also successfully executed.
But now I am wondering... Why wasn't EF Core connecting to the (LOCAL) DB before I followed the guide and DID it work on project A, but not on B....?
EDIT
After some more research, I discovered the specific action from the guide that helped me to resolve the error that I got. It was to set the TCP Port to 1433 in the Sql Server Configuration Manager. Apparently this field was empty... But it leaves me with 1 question.
Why did the add command DID work without a port specified and was only the remove command complaining about the connection?
EDIT2
And yet another new finding, when adding the following method to the AppDbContext class:
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("foo");
base.OnConfiguring(options);
}
The add command works fine, but the remove command complains about the incorrect format of the connectionstring
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
So we can conclude from this that the add command DOESN'T require a valid connectionstring (as it does nothing with the DB), while the remove command DOES require a valid connectionstring... but why??? It does nothing with the DB, right?
As an answer to my own question, here an explanation on how the add and remove migrations work.
The add migration functionality DOES require a valid string as the connectionstring in the context, but it DOESN'T need to be a correct connectionstring, as EF Core is not realy connecting to the DB.
For the remove migration functionality, you DO require a correct connectionstring, as EF Core makes a connection to the DB to compare the local list of migrations with the _EFMigrationsHistory table to check if there are any migrations that has not been applied to the DB. Because the remove functionality can only remove PENDING migrations. So not any migrations that have already been applied to the DB.

Entity Framework Core Error: An error occurred using the connection to database '' on server 'localhost'

I have made an ASP.NET Core 3.1 Web-based application and want to use MySQL as the database.
I have been following along with some YouTube tutorials on creating MySQL database with ASP.NET Core 3.1 [code first approach] including a tutorial from this site:
https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-3.1&tabs=visual-studio
I have created a DataModel Class, added a service to UseMySQL to the Startup.cs Class and created an AppDBContext Class that implements DbContext Class.
When I run this command in the Package Manager Console: Add-Migration InitialDatabase the application is creating a migration successfully.
When I run update-database it is throwing this exception:
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database '' on server 'localhost'.
An error occurred using the connection to database '' on server 'localhost'.
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySQL' call.
When I call the EnableRetryOnFailure(); function as required, I am facing this exception:
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database '' on server 'localhost'. An error occurred using the connection to database '' on
server 'localhost'.
What could be the issue?
Where am I getting it wrong?
If you have links to useful articles about using MySQL Database with ASP.NET Core I would appreciate or your help on this particular issue.
I am using Visual Studio IDE 2019 and ASP.NET Core 3.1.1
Additional Code:
This is the Startup.cs Class:
private IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// database connection string configuration
services.AddDbContextPool<AppDBContext>(options => options.UseMySql(_configuration.GetConnectionString("DatabaseConnectionString"),
mySqlOptionsAction: options => { options.EnableRetryOnFailure(); }
));
services.AddMvc();
}
This is the connection string in appsettings.json:
"ConnectionStrings": {
"DatabaseConnectionString": "Server=localhost;Database=MyAppDB;user=root;Password=123;"
}
I think I found the root of the problem. This error also occurs when the connection to the database couldn't have been established. Make sure the information in your connection string is correct. This error message is very misleading, I spent couple of hours figuring this out because of it.
You can try this way
Install package Pomelo.EntityFrameworkCore.MySQL
Add services at Startup.cs
services.AddCors();
services.AddDbContext(options => options.UseMySql(Configuration.GetConnectionString("DatabaseConnectionString")));
change connection string at appsettings.json
"ConnectionStrings": {
"DatabaseConnectionString": "server=localhost;port=3306;database=MyAppDB;user=root;password="
}
*change the port number according to your MySQL server
4.Run these commads at Package Manager Console for data migration
Add-Migration InitialCreate
Update-Database
You can look at the project at github, for better understanding
In my case, I just added the database port separately.
changed this from
MySQL": "server=mysqlserver.com:3306;user=db_user;password=db_pass;database=database_name"
to
MySQL": "server=mysqlserver.com;port=3306;user=db_user;password=db_pass;database=database_name"
Your connection string doesn’t seem to be right or EF is not able to pull it. You ll need to check the docs and select the correct project before running the update.
Confirm the connection string using this post:
https://www.c-sharpcorner.com/UploadFile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/
You can try this workaround to specify the connection with the command, PS you ll need to update the provider name for MySql:
Update-Database -Verbose
-ConnectionString "CONNECTIONSTRING"
-ConnectionProviderName "System.Data.SqlClient"
-StartupProjectName WEBSITE_PROJECT -ProjectName MIGRATION_PROJECT
I had the same problem, this error occured the me when the connection string was wrong. In my case it was the port (by default 8457). Have you tried specifying it in the connection string?
Your steps don't seem to include installing a local instance of MySQL Server, which could be why you cannot find a server... because its not installed!
MSSQL (localdb) is bundled with Visual Studio 2019 (with the Data Modelling and Processing workload) but MySQL still needs to manually installed.
Have you tried installing a supported version of MySQL Server with your EF Provider?
I had the same problem. This error occured when a MariaDB and the web app runs on the same host.
A hint for a solution you can find here:
Now that your MariaDB server installation is setup to accept
connections from remote hosts, we have to add a user that is allowed
to connect from something other than 'localhost' (Users in MariaDB are
defined as 'user'#'host', so 'chadmaynard'#'localhost' and
'chadmaynard'#'1.1.1.1' (or 'chadmaynard'#'server.domain.local') are
different users that can have completely different permissions and/or passwords.
In my case a user mdbuser is allowed to connect from hosts 192.168.178.% according to the table mysql.user.
So I added a second user named mdbuser with localhost and the error disappeared:
GRANT ALL PRIVILEGES ON *.* TO 'mdbuser'#'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
This also happens if you forget to specify the Connection String in case of using SqlServer in NET6:
Wrong:
var conString = builder.Configuration.GetConnectionString("MyDbConnection");
builder.Services.AddDbContext<MyDbContext>(options => options.UseSqlServer());
Correct:
var conString = builder.Configuration.GetConnectionString("MyDbConnection");
builder.Services.AddDbContext<MyDbContext>(options => options.UseSqlServer(conString));
Suffered same error on IIS 8.5. The connection string was wrong, fixed it but error still showed.
Solution: Recycle the app pool. Changing the .json file doesn't restart de app so you need to do it.
Hope it helps somenone.
In my case it was a permission issue with AWS RDS.
I had to add an inbound rule in the security group with my IP. I was then able to connect

A network-related or instance-specific error occurred while establishing a connection to SQL Server while migration with asp.net core migration

I, am using package manager console to perform the database migration.
I used the following command
Add-Migration init
This command work perfectly and created the migration object as see in the below image
Now I am using
Update-Database
command to create the database however I, am getting an error as shown below
I have used the solution provide here and this question.
However, this solution is not working for me from visual studio.
I, am able to use the sql server from SSMS. This error is from visual studio.
Here is the firewall screen shot
Might be your connection to SQL is not started. Just follow below steps:
1. Go to run command or press Windows+R key and enter services.msc.
2. Find SQL Server (MSSQLSERVER) there and right click on it and click on start option.
Then retry.
This solution work for me.I change the statrtup.cs file as per the below repo
https://github.com/bricelam/Sample-SplitMigrations
Add migration with different assembly
In My Case
appsettings.Development.json contain another server Name that was collupse thats why i never noticed .

EF 6 Update-Database failed with provider

I'm switching from a MySql database to a Sql Server database.
I remove all related data to mysql from configuration and web.config.
But I still get this issue on Update-Database command in Package manager console:
Update-Database -Verbose
Using StartUp project 'B2Peer.Web'.
Using NuGet project 'B2Peer.EntityFramework'.
Specify the '-Verbose' flag to view the SQL statements being applied to the
target database.
Target database is: 'b2peer' (DataSource: .\SQLLOCAL, Provider:
System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
System.Data.Entity.Core.MetadataException: Schema specified is not valid.
Errors:
(0,0) : error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'MySql.Data.MySqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
I cleaned the solution and rebuild
Is there any cache files that I can clean to avoid EF to look for a provider Mysql ?
Note: I searched with notepad++ in all files in my solution folder and there are nothing related to my search 'mysql' ... So why EF still looking for this provider ...
Finally It was fixed.
After multiple clean, build, launch website with automatic migration to true.
Then Update-Database has stopped to give this error...

EF7 Reverse Engineer Existing DB - Timeout error

I am executing the following command (executing this inside the asp.net 5 project folder using cmd)
dnx ef dbcontext scaffold "Data Source=SQL2K14;Initial Catalog=movies;Integrated Security=False;User ID=sa;password=pass" EntityFramework.MicrosoftSqlServer --outputDir Models
and get the following error
System.Data.SqlClient.SqlException (0x80131904): A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.) period has expired.)
I know for a fact there is nothing wrong with my connection string because i use the same exact connecting string from the same exact machine (inside the asp.net project) using SqlCommand to open the connection and retrieve stuff. So this would not be a network related issue or connection string at all, its purely to do with the dnx ef dbcontext command
According to http://ef.readthedocs.org/en/latest/getting-started/aspnet5/existing-db.html#reverse-engineer-your-model this is the way to reverse engineer it but I am not sure if they updated it to be done another way as this suggests its complex and it will be simplified but not sure when it will be
My commandline which works for comparism is (note connection string format is different)
dnx ef dbcontext scaffold "Server=myserver;Database=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true" EntityFramework.MicrosoftSqlServer --context ReportingDbContext --output-dir Models
Run from the root of my project directory

Categories

Resources