MySQL Blog Archive
For the latest blogs go to blogs.oracle.com/mysql
MySQL Connector/NET provider for Entity Framework Core 3.1

Hello MySQL Connector/NET community,

Keeping an ongoing pace to support the latest technologies, we are pleased to announce the latest updates regarding MySQL Connector/NET and Entity Framework Core.

As you may know, Entity Framework Core 3.1 is the latest and long-term support (LTS) release, meaning that it will be supported for at least 3 years. It has a primary goal to polish the EF Core 3.0 version and reintroduces support for .NET Standard 2.0, so it will run on .NET Frameworks versions that support the standard. In our continuous effort to keep up on the latest technologies, we would like to share with you that our latest GA release, Connector/NET 8.0.20, comes with full support for EF Core 3.1.

Let’s have a short demonstration on how to use Connector/NET and EF Core. We are going to use the Code First process to create the database in our server and build up our Entity Model in a Console Application.

Prerequisites:
– Visual Studio 2019
.NET Core 3.1 SDK
MySQL Server
– Connector/NET 8.0.20 (this could be obtained on our site or by using NuGet)

We are going to start by creating a console application and in this case, we are going to do it by using .NET Core CLI:

dotnet new console -o EFCoreSample

If we look into the .csproj file of our application, we can see that the TargetFramework have been set to netcoreapp3.1. Then we need to add our EF Core Connector/NET NuGet package to the project:

dotnet add package MySql.Data.EntityFrameworkCore –-version
8.0.20

So now that we have our console application and the EF Core Connector/NET package installed, we can start writing our context and entity classes. Create a class called Model.cs in the project directory with the following code:

using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using MySql.Data.EntityFrameworkCore.DataAnnotations;

namespace EFCoreSample
{
  public class LibraryContext : DbContext
  {
    public DbSet<Book> Book { get; set; }
    public DbSet<Publisher> Publisher { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseMySQL("server=localhost;database=efcoresample;user=efcore;password=");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      base.OnModelCreating(modelBuilder);

      modelBuilder.Entity<Publisher>(entity =>
      {
        entity.HasKey(e => e.ID);
        entity.Property(e => e.Name).IsRequired();
      });

      modelBuilder.Entity<Book>(entity =>
      {
        entity.HasKey(e => e.ISBN);
        entity.Property(e => e.Title).IsRequired();
        entity.HasOne(d => d.Publisher)
          .WithMany(p => p.Books);
      });
    }
  }

  [MySqlCollation("latin1_spanish_ci")]
  public class Book
  {
    [MySqlCharset("latin1")]
    public string ISBN { get; set; }

    public string Title { get; set; }
    public string Author { get; set; }
    public string Language { get; set; }
    public int Pages { get; set; }
    public virtual Publisher Publisher { get; set; }
  }

  public class Publisher
  {
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Book> Books { get; set; }
  }
}

Now that we have our context and entity classes set up, we can start using our model the way we want to, in this example we are going to insert a couple of records and then print them in screen. On the main class of our project (Program.cs) we are going to add two methods, one to insert data and another to print it:

using System;
using System.Text;
using Microsoft.EntityFrameworkCore;

namespace EFCoreSample
{
  class Program
  {
    static void Main(string[] args)
    {
      InsertData();
      PrintData();
      Console.ReadKey();
    }

    private static void InsertData()
    {
      using (var context = new LibraryContext())
      {
        // Creates the database if not exists
        context.Database.EnsureCreated();

        // Adds a publisher
        var publisher = new Publisher
        {
          Name = "Mariner Books"
        };
        context.Publisher.Add(publisher);

        // Adds some books
        context.Book.Add(new Book
        {
          ISBN = "978-0544003415",
          Title = "The Lord of the Rings",
          Author = "J.R.R. Tolkien",
          Language = "English",
          Pages = 1216,
          Publisher = publisher
        });
        context.Book.Add(new Book
        {
          ISBN = "978-0547247762",
          Title = "The Sealed Letter",
          Author = "Emma Donoghue",
          Language = "English",
          Pages = 416,
          Publisher = publisher
        });

        // Saves changes
        context.SaveChanges();
      }
    }

    private static void PrintData()
    {
      // Gets and prints all books in database
      using (var context = new LibraryContext())
      {
        var books = context.Book.Include(p => p.Publisher);
        foreach (var book in books)
        {
          var data = new StringBuilder();
          data.AppendLine($"ISBN: {book.ISBN}");
          data.AppendLine($"Title: {book.Title}");
          data.AppendLine($"Publisher: {book.Publisher.Name}");
          Console.WriteLine(data.ToString());
        }
      }
    }
  }
}

And that’s it! A quick look on how to build an EF Core 3.1 application using MySQL Connector/NET as the provider. This is just a small demonstration of what ypu can do with EF Core. There are many features in EF Core to use and we are pleased to tell you that Connector/NET has full support for them.

We hope you find this information useful to start using MySQL Connector/NET with the most recent technologies. Your feedback is always welcome and all your comments inspire us to keep improving so that we offer you a product with top quality.

Finally, here are some links that could be useful for you:

We hope to hear from you!