0% found this document useful (0 votes)
4 views

Code first with mysql

This document provides a tutorial for using Entity Framework 6 (EF6) with MySQL in an ASP.NET API project, detailing prerequisites, project setup, and database creation. It covers the installation of necessary NuGet packages, the creation of a DbContext class, and the configuration of a connection string in the Web.config file. Additionally, it explains how to enable migrations and update the database to reflect changes made in the code.

Uploaded by

ndellasokeng129
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Code first with mysql

This document provides a tutorial for using Entity Framework 6 (EF6) with MySQL in an ASP.NET API project, detailing prerequisites, project setup, and database creation. It covers the installation of necessary NuGet packages, the creation of a DbContext class, and the configuration of a connection string in the Web.config file. Additionally, it explains how to enable migrations and update the database to reflect changes made in the code.

Uploaded by

ndellasokeng129
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

I was using the Microsoft tutorial documentation for Entity

Framework 6 (EF6) in combination with MySQL. Their


documentation on using EF6 with SQL Server is very good, but I
found some hick ups while implementing it with MySQL. To save
you some time in going back and forth between Microsoft and
MySQL documentations, here’s a one-page tutorial :)

I’m going to use ASP.NET API, build the data layer code-first and do
code-based registration.

Prerequisites

I’m asuming you know how to program, what an ORM does (why
would you otherwise want to use EF6?) and that you want to install
on a Windows machine. I’m using the following (NuGet) versions:

• .NET 6

• Visual Studio 2022

• Entity Framework 6 (NuGet 6.4.4)

• MySQL (NuGet 8.1.0)

• MySQL Workbench

Create an ASP.NET API project

In Visual Studio, create yourself a project if you don’t have on


already.
Open your NuGet Package Manager (not the console, see Tools or
right-click on your project). Install the following packages:

EntityFramework
MySql.Data
MySql.Data.EntityFramework

Create your DbContext

The DbContext is the part that magically works with your database.
Trust the magic :)

Add a new class and name it “SchoolContext”. Let it inherit from


“DContext”. See code below.

[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class SchoolContext : DbContext
{

public SchoolContext() : base("SchoolContext")


{
}

public DbSet<Student> Students { get; set; }


public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
}

Note that I’m calling the base of DbContext with a string


“SchoolContext”. This is a name or connection string, so you could
also call the connection string directly here. The “SchoolContext” you
see here now will come from another file, just a bit lower on this
page.
Also note that above the line “public class SchoolContext :
DbContext” is an attribute that is the type of SchoolConfiguration
(the class made earlier).

The [DbConfigurationType(typeof(MySqlEFConfiguration))] will make


sure that the dependency resolver is set to MySQL (and some other
stuff is done in the background you don’t need to worry about).

Each DbSet<T> will be an entity, or table, in your database. These


models you design as POCOs (Plain Old C# Objects). Just make
some classes with public get-set proporties, like below.

public class Student


{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

To code how each field in a table will look (what the max. char size of
a string will be for instance) you can code in the override method of
OnModelCreating in the SchoolContext using FluidAPI or you use
the annotations in the models themselves.

ConnectionString

The connectionstring, as I mentioned before, is given to the


DbContext in the SchoolContext, using the base method on the
constructor. To have it connect to a real connectionstring, find
yourself the Web.config file in the root directory of your solution. If
it’s not there, create it. Now you can add this part to it (note that
<configuration> if your root tag):

<configuration>
<connectionStrings>
<add name="SchoolContext"
providerName="MySql.Data.MySqlClient"

connectionString="server=localhost;port=3306;database=SchoolDatabase;uid=r
oot;password=YourSuperSafePassword" />
</connectionStrings>
</configuration>

Create the database from code

Now comes the part where I forgot how it worked, and what I think
is not explained properly in the tutorial from Microsoft: create the
actual database from code.

In VisualStudio click on Tools > NuGet Package Manager > Package


Manager Console. Make sure the Default project is the project where
you have your database code in. To see that EF6 is correctly
installed, type Get-Help EntityFramework and press enter. You will see
a nice unicorn and a list of available commands.

First you have to enable migrations using the “Enable-Migrations”


command. After that has succeeded you find a new folder in your
solution with a new file “Configuration.cs”. In this file you can seed
your database with initial rows, if needed.

You can add your first migration using “Add-Migration [migation-


name]”. For the first migration I usually name it
“Initialize_Database”. Make sure to have DbSet<T> properties in
your DbContext, otherwise it won’t find any changes. A few more
files will be generated for you, which will insert new tables in your
database and provide all the necessary properties to each column.

Now, run “Update-Database” to put this migration to work. If it


succeeds you will find in your MySQL Workbench that you have a
new database with your new tables :)

You might also like