MySQL Entity Framework 6: Database First. How to create classes?

Harald Coppoolse picture Harald Coppoolse · Jan 16, 2017 · Viewed 7.6k times · Source

Until now I've been using EF6 with Visual Studio, mostly code first, rarely database first.

To import some test data, someone gave me the connection to a database in MySQL. In MySql Workbench I can query data, so the connection works.

Now I want to create an Entity Framework Database First project and import the database model. In Visual Studio

  • Create Project,
  • Add nuget: Entity Framework newest version (6.1.3)
  • Add nuget: MySql.Data.entities for EF 6
  • Add new item

And now? There is an EF 6.X DbContext generator, but that one does not work until I've got the model

I can do what I normally do:

  • select ADO.NET entity data model
  • EF Designer from database
  • And now? How to connect to MySql?

Addition

Mehmet referred me to MySql EF6 Support (thanks Mehmet), a page that came first when I googled. Maybe this is the correct way, but I don't understand whtat it says The first steps: add the connection string and add the reference (= install nuget package?) I can manage, but after that it's all Greek to me:

  • Set the new DbConfiguration class for MySql. THE new DbConfiguration class? Which DbConfiguration class? Where, and how to set it for MySQL?
  • Add the DbConfigurationTypeAttribute to the DbContext. Alas, I haven't got a DbContext yet, it's not code first, but database first: some wizard is supposed to determine the DbSets in the DbContext for me.

So maybe this is the way to go, but this is too cryptical for me.

Answer

Roberto Garcia picture Roberto Garcia · Dec 24, 2020
  1. Need to install some NuGet on your NuGet administrator
    microsoft.EntityFrameworkCore
    microsoftEntityFrameworkCore.Tools
    Microsoft.NETCore.App
    Pomelo.EntityFrameworkCore.MySQL
    
  2. After having all your NuGet, you need to apply this to your Package Console Administrator:
    Scaffold-DbContext 
    "Server=localhost;Database=database_name;User=root;Password=123456;" 
    "Pomelo.EntityFrameworkCore.MySql" -Outputdir Models
    

This will create a context for all your models and will also create some models for your data base.