1-561-880-4109

Entity Framework with MySQL - Console C# Applicati…

Claude JOASIL March 25, 2016

Entity Framework with MySQL - Console C# Application

When creating a new project with visual studio, the default database selected is SQL Server. There are many reasons why you may want to use MySQL instead of SQL Server for data storage. The first one that comes to mind is the price. MySQL is free and can be used on more environment than SQL Server - Doesn't really matter for this article since we're showing you how to use Entity framework with MySQL, but worth mentioning mainly if you plan to isolate your application and database servers i.e having them run on different environments.

In this article we will be creating a simple Console C# application to show you how to use Entity Framework with MySQL. Let's get started:

  1. Open Visual Studio, I am currently using VS 2015
  2. Create a new Project (give it a name and select desired location and click OK)

  3. We need to download two nuget packages:
    EntityFramework and Mysql.Data.Entities (Connect/Net for MySQL)
    - Right click on your project name and click "Manage Nuget Packages"


    -  Type "Entity Framework" in the search box, select EntityFramework and click Install. See image below:

    -  Type "MySQL"  in the search box to download the other package see image below:


  4. Now we need to add the MySQL Provider to app.Config
    - Open the file App.config
    - Locate the "entityframework" section and the "providers" section
    - add 
    <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
    inside the "providers" section. The entityFramework section should look like below after this step

    Build the application to make sure everything works fine so far.
  5. While you're in the App.config file, add a "connectionstring" section below the "configSections" section

     <connectionStrings> <add name="MyConnectionString" connectionString="server=localhost;user id=<MYUSERNAME>;password=<MYPASSWORD>;database=<MYDB>;persistsecurityinfo=True" providerName="MySql.Data.MySqlClient" /> </connectionStrings>

    Note: Make sure you replace <MYUSERNAME>, <MYPASSWORD>, <MYDB> with your own information


  6. For simplicity sake, we've added the model and the AppDBContext to the Program.cs file. Please feel free to create a different file for each.

    Modify the Program.cs file to look like below:


  7. Run the application. You should have a new database created with the name you supplied and a Student table with one record.

Happy Coding!