Using MySql in ASP.NET Core
August 26, 2016 by Anuraj
C# asp.net core MySql
This post is about using MySql in ASP.NET Core. Few days back MySql team announced release of Official MySql driver for ASP.NET Core. You can find more details about the announcement here. In this post we will explore how to use MySql driver and EF Migrations for MySql. Here I have created a Web API project using yoman aspnet generator. And you need to add MySql drivers for ASP.NET Core in the project.json file. Here is the project.json file.
The “Microsoft.EntityFrameworkCore.Tools” package is to execute the migrations. We are not using it right now. Now you need to create the Model class and DbContext class. Here I am using a simple book model and Db Context with books DbSet property.
Here is the DbContext implementation.
Now you need to modify the ConfigureServices method to use MySql.
Now you are ready to execute SQL Statements against MySql. So I have created a controller class for Book entity. And in the controller constructor I am making sure database is created.
Now if you run the app and try to access the Books controller, books table will be created.
And here is the phpmyadmin console, with Books table data.
EF Code First Migrations
The Migrations feature enables you to change the data model and deploy your changes to production by updating the database schema without having to drop and re-create the database. You can use “dotnet ef” command to create and execute the migrations. In the project.json you have already added the References and Tools for EF migrations. I have added an Author table and created a migrations.
It is creating the migration folder and C# scripts for the migration. Now you can run the database update command. And here is the result of the database update command.
It is failing :( It is throwing a Not Implemented Exception. I am not sure actually it is not implemented or I missed some configuration. Hope MySql team will work on this and will fix the issue.
Happy Programming :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub