MySQL Blog Archive
For the latest blogs go to blogs.oracle.com/mysql
HowTo: Starting with MySQL EF Core provider and Connector/Net 7.0.4

This article shows the essential parts of the configuration for a quick console application using the .NET Core command-line (CLI) tool. The application will show how to create an EF Core model and some basic operations that can easily be done in Windows, Linux or OSx.

1. Requirements

Install the sdk, framework and tools:

Windows:
Install
– .NET Core SDK for Windows direct link here
– Visual Studio 2015 Update 3* here’s the publication page with more information about the update.
– .NET Core 1.0 tooling for Visual Studio direct link here

Linux:
An official detailed guide can be followed here.

OSx:
Follow the instructions and download the official installer here

2. Create the console application

This tutorial shows instructions for developing the application in Windows, but the same application can be done just changing the commands to the equivalent in the corresponding platform.

1. Create a folder where the new project will be saved.

On a command prompt type:
> mkdir efcore

2. Create the project
> cd efcore
> dotnet new

3. Create an appsettings.json file to hold your connection string information. Example:

{
"ConnectionStrings":
 {
    "SampleConnection": "server=localhost;userid=root;pwd=;port=3305;database=sakila;sslmode=none;"
 }
}

Note: Adjust your server settings accordingly to your MySQL server configuration and user.

Notice the sslmode key in the connection string. This tells the server to use a plain connection instead of a secured one. If you like to use ssl mode then change this value to Preferred.

4. Modify the project.json to add the EntityFrameworkCore dependencies, add the MySQL references and specify that the appsettings.json file must be copied to the output (buildOptions section) so it becomes available to the application when building it.

The result should look like the following:

{
    "version": "1.0.0-*",
    "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true,
    "copyToOutput": {
    "include": "appsettings.json"
    }
},
"dependencies": {
     "Microsoft.Extensions.Configuration": "1.0.0",
     "Microsoft.Extensions.Configuration.Json": "1.0.0",
     "Microsoft.EntityFrameworkCore": "1.0.0",
     "MySql.Data.Core": "7.0.4-IR-191",
     "MySql.Data.EntityFrameworkCore": "7.0.4-IR-191"
   },
"frameworks": {
     "netcoreapp1.0": {
     "dependencies": {
     "Microsoft.NETCore.App": {
     "type": "platform",
     "version": "1.0.0"
  }
},
   "imports": [
      "dnxcore50",
      "portable-net452+win81"]
  }
 }
}

5. After project.json modifications a restore of the packages in the application is mandatory. This command will download all the dependencies needed. In the console window type the following:

> dotnet restore

6. Create a database context for Entity Framework
Inside a text editor, or the IDE you prefer to use, create a EmployeesContext.cs file.
Here is an example of a context with some entities.

namespace ConsoleApplication
{
using Microsoft.EntityFrameworkCore;

/// <summary>
/// The entity framework context with a Employees DbSet
/// </summary>
public class EmployeesContext : DbContext
{
public EmployeesContext(DbContextOptions<EmployeesContext> options)
: base(options)
{ }

public DbSet<Employee> Employees { get; set; }
}

/// <summary>
/// Factory class for EmployeesContext
/// </summary>
public static class EmployeesContextFactory
{
public static EmployeesContext Create(string connectionString)
{
var optionsBuilder = new DbContextOptionsBuilder<EmployeesContext>();
optionsBuilder.UseMySQL(connectionString);

//Ensure database creation
var context = new EmployeesContext(optionsBuilder.Options);
context.Database.EnsureCreated();

return context;
}
}

/// <summary>
/// A basic class for an Employee
/// </summary>
public class Employee
{
public Employee()
{
}

public int Id { get; set; }

[MaxLength(30)]
public string Name { get; set; }

[MaxLength(50)]
public string LastName { get; set; }
}
}

7. Replace the contents of the Program.cs file with the following code:

namespace ConsoleApplication
{
using System;
using Microsoft.Extensions.Configuration;

public class Program
{
public static void Main(string[] args)
{

var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

var configuration = builder.Build();

string connectionString = configuration.GetConnectionString("SampleConnection");

// Create an employee instance and save the entity to the database
var entry = new Employee() { Name = "John", LastName = "Winston" };

using (var context = EmployeesContextFactory.Create(connectionString))
 {
   context.Add(entry);
   context.SaveChanges();
 }

Console.WriteLine($"Employee was saved in the database with id: {entry.Id}");
  }
 }
}

8. Build the application with the following command:

> dotnet build

9. Run the application

> dotnet run

The output from this console application is:

Employee was saved in the database with id: 1

Conclusion

Entity Framework is a well known technology for data access in .NET applications. With this new Core version, developers can create applications for Windows, Linux and OSX without changing the application code. The MySQL provider and EF core is a great combination for applications that target the new .NET Core version.

We love to hear your thoughts or any comments you have about our product. Please send us your feedback at our forums, fill a bug at our community site, or leave us any comment at the social media channels in Twitter or Facebook.

Enjoy and thanks for the support!

On behalf of the MySQL Connector/Net team