MySQL is a database management system from Oracle that currently supports Entity Framework through MySQL ADO.NET Connector, which is a fully-managed ADO.NET driver for MySQL. I will go through the steps in setting up MySQL with Entity Framework 6.1.+, using Visual Studio.
PREREQUISITES
- Visual Studio
Download free community version here. - MySQL Server
Download here. - ADO.NET driver for MySQL (Connector/NET)
Download here. - Microsoft Entity Framework 6.1.+
Adding Entity Framework
Download Entity Framework from NuGet in Visual Studio. This will automatically reference all the required Microsoft Entity Framework assemblies in your project.
Or
Run this command in Package Management Console to download Entity Framework.
Pm> Install-Package EntityFramework
Reference MySQL Assemblies (NB.These assemblies are available after installing MYSQL Connector for .NET)
- MySQL.Data
- MySQL.Data.Entity
Setting up the connection string in your Web.Config or App.Config
Set the connection string to your existing MySQL database
- <connectionStrings>
- <add name="SellRightDb" providerName="MySql.Data.MySqlClient"connectionString="server=localhost;userid=[your userid];password=[your password];database=sellright;persistsecurityinfo=True"/>
- </connectionStrings>
Entity Framework configuration
Configuring MySQL to use Entity Framework adds the block below to your Web.config or App.config.
- <entityFramework>
- <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
- <providers>
- <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
- <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers>
- </entityFramework>
Create a simple Model class
- class Product {
- public int ProductId {
- get;
- set;
- }
- public string ProductName {
- get;
- set;
- }
- public double Price {
- get;
- set;
- }
- public int Quantity {
- get;
- set;
- }
- }
Creating Your DBContext class
Import Namespaces
- using System.Data.Entity;
- using MySql.Data.Entity;
Configuring your DBContext class
-
- [DbConfigurationType(typeof(MySqlEFConfiguration))]
- class SellRightContext: DbContext {
-
- public DbSet < Product > Products {
- get;
- set;
- }
- public SellRightContext()
-
- : base("SellRightDb") {}
- }
- `
Enable Code First Migration
PM> Enable-Migrations
Add Code First Migration
PM> Add-Migrations [Give Your Migration Settings A name]
Update the database (Specify Verbose to see the SQL Query, i.e being executed).
PM> Update-Database -Verbose
NB.You should see your created product table.