Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to MySQL server using Entity Framework Core

I am using Visual Studio 2019 community edition. I want to connect to MySQL using Entity Framework core. I do not want to use Entity Framework 6.

I am running into following issues:

  1. I created a new project using "ASP .NET CORE App and ASP .NET CORE Web App" template and it does not show option to add Entity Framework.

enter image description here

  1. If I use tools > Connect to Database option from menu, I do not see option to connect to MySQL. How can I enable this option.

enter image description here

like image 713
OpenStack Avatar asked Oct 25 '25 19:10

OpenStack


1 Answers

Step by Step - Database First

First install these packages

  1. Microsoft.EntityFrameworkCore.Design

So on Powershell go to project folder [right click on project and select open in terminal (visual studio)]

enter image description here

Now, you can run this command

enter image description here

dotnet ef dbcontext scaffold "Servel=localhost;Database=tempSQLonNetCore;user=root;password=;" "Pomelo.EntityFrameworkCore.MySql"

If your connection is true, your DbContext Generated and entities adding to your project.

Now you must inject DbContext, Described in the Codefirst section


Step by Step - Code First

First install these packages

  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.Tools
  3. Pomelo.EntityFrameworkCore.MySql

Add connection string look like in appsetting.json

"ConnectionStrings" : {
    "DefaultConnection" : "Servel=localhost;Database=tempSQLonNetCore;user=root;password=;"
}

**Now, Create your DB context **

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }

    // Your Entities
}

finally configure the app for connecting

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => {
     options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});

Now you can use Migration if you need to create or update your database Migration

like image 103
thisisnabi Avatar answered Oct 27 '25 10:10

thisisnabi