Reputation: 361
How can I point my ASP.NET MVC application to a MySQL database?
Upvotes: 2
Views: 2233
Reputation: 41
To create a connection with the database :
First of all install the following packages from Nuget Manager
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
First Open Sql Server Management Studio, then click on the charger icon on the top in the left panel. You will see a popup. Enter the server name (remember it) and click ok.
Second, go to appSettings.json enter the following lines of code
"ConnectionStrings": {
"DefaultConnection": "Server=Enter the Server name here;Database=Name anything you want;Trusted_Connection=True;TrustServerCertificate=True"}
-Make sure to give a comma before it. And enter the name of the server that i asked you to remember.
inside your main project create a "data" folder and inside create a class by the name of "ApplicationDbContext.cs". Inside the class file paste the following code snippet which is just a kind of syntax
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
}
//Make sure to import the entityframeworkcore in this file
Next, got to Program.cs and just above the "var app = builder.Build();" line paste the following code
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))
);
You might need to import the entity framework core in this file as well. Or simply add "using Microsoft.EntityFrameworkCore;" in program.cs and ApplicationDbContext.cs file
Last step is to go to tools -> nuget package manager -> package manager console , in the console write the command update-database
and click enter
Upvotes: 0
Reputation: 1039438
Once you download the MySQL ADO.NET Connector it's a simple matter of referencing the assembly in your project and writing the queries, the same way you would do in any other application, nothing specific MVC:
using (var connection = new MySqlConnection(ConnectionString))
using (var cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT name FROM foo;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("name"));
// TODO: do something with the name ...
}
}
}
Upvotes: 3