In this article, I will explain step by step how to connect to an existing MySQL database in a ASPNET web application using Entity Framework (EF) Core. This process is described by Microsoft as Reverse Engineering as opposed to the Migration process. In short, you use Migration when you start building a new application from scratch including the database; and you use Reverse Engineering when you build your application using an existing database.

1. Create an ASPNET web application

Create any type of application you need. I’m trying to build an API app, so this is what I created.

> dotnet new web myWebApi

2. Add References for EF Core

If you have installed NuGet Package Manager, you should be able to search these packages and install them through the manager. In case you haven’t, you can still install them through Terminal.

> dotnet add package Microsoft.EntityFrameworkCore.Design --version 3.1.0
> dotnet add package Pomelo.EntityFrameworkCore.MySql --version 3.1.1

The next package we will add as a CLI tool. So after the installation, my CSPROJ looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.0"/>
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1"/>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3"/>
  </ItemGroup>
</Project>

And then we can restore the libraries.

> dotnet restore

After restoring, we can now check EF is installed properly. You should see the EF icon which is a unicorn in your terminal.

> dotnet ef

3. Generate Domain Models from DB Schema

This command below works by reading table information and creating a model class which matches exactly to the table. You can of cause customize your model class based on your application needs.

> dotnet ef dbcontext scaffold "server=DBSERVERNAME;database=DBNAME;user=DBUSERNAME;pwd=PASSWORD;" "Pomelo.EntityFrameworkCore.MySql" -o .\Models -t TABLENAME

Now we should be able to test the connection by doing some CRUD operations. The only issue I had was EF Core didn’t like zero date time (0000-00-00 00:00:00) in my MySQL DB. And I need to add below setting to my configuration.

Allow Zero Datetime=true;Convert Zero Datetime=true

Share: