MySQL with Entity Framework Core in ASP.NET Core


.NET Core offers.NET developers a great way to create cross-platform applications. If you want to create a web app with some database support, most likely you will use Entity Framework (EF) Core and ASP.NET Core. In this blog post, I'd like to give you some tips if you choose to use MySQL.

1. Db Provider choice

Although there're a few MySQL providers to choose from in the official EF Core Docs site, I would recommend the most popular Pomelo.EntityFrameworkCore.MySql. I tried other providers and it gave me issues here and there.

Specifically, you can use the following code to add a DbContext in your service configuration:

services.AddCors();

services.AddDbContext<KnowledgeContext>(options => options.UseMySql(Configuration["MySqlConnStr"]));

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

And don't forget to pass the DbContext to your controller's constructor.

2. Use Fluent API instead of Data Annotation

This is more of an EF Core tip than a MySQL one. Certain restrictions such as foreign keys can only be specified with  the Fluent API.

3. Where to call Database.EnsureCreated

Again, an EF Core tip. DbContext.Database.EnsureCreated() is new method to ensure that the database and the required schema for the context exist. The database and the schema will be created if they don't exist. However, in ASP.NET Core, every time a request comes, a controller's constructor is called. So you probably want to put the EnsureCreated call in the Startup class. Please refer to https://stackoverflow.com/questions/36958318/where-should-i-put-database-ensurecreated.

Comments (0)

Skip to main content