There are currently two MySQL providers for EF that I know of: Connector/Net and Devart's dotConnect for MySQL. Devart's provider has a few more features, but it is also a commercial product. In the spirit of FOSS, we will be using the Connector/Net provider for this walkthrough. I encourage you to keep the Devart provider in mind, however, if your project requires that extra level of support.
Create the Application
For simplicity, we will be using a Console Application, but the basic steps are the same regardless of project type.- Open Visual Studio
- Select File -> New -> Project...
- Select Console Application
- Name the project
- Click OK
Create the Model
For our model, we'll be borrowing pieces from the Chinook Database (a cross-platform, sample database). Specifically, we will be using Artists and Albums.Add the following two classes to your project.
public class Artist { public Artist() { Albums = new List<Album>(); } public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Album> Albums { get; set; } } public class Album { public int Id { get; set; } public string Title { get; set; } public int ArtistId { get; set; } public virtual Artist Artist { get; set; } }
Create a Context
In EF, the context becomes your main entry point into the database. Before we define our context though, we will need to install Entity Framework.- Select Tools -> Library Package Manager -> Package Manager Console
- Inside the Package Manager Console (PMC) run Install-Package EntityFramework -Version 4.2
Note: We're using EF 4.2 because there's a bug in the current version of Connecter/Net that prevents it from properly creating the database. Please see my workaround if you're interested in using the latest version of EF.Now, add the context class to your project.
class ChinookContext : DbContext { public DbSet<Artist> Artists { get; set; } public DbSet<Album> Albums { get; set; } }
Install the Provider
In order to connect to MySQL databases, we will need to install an appropriate ADO.NET and Entity Framework provider. Luckily, the provider we're using is available via NuGet.- Inside PMC, run Install-Package MySQL.Data.Entities
<system.data> <DbProviderFactories> <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description="Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" /> </DbProviderFactories> </system.data>
Add a Connection String
In order to connect to the right database, we need to add a connection string to the App.Config. Anywhere inside the configuration element, add the following fragment.<connectionStrings> <add name="ChinookContext" connectionString= "server=localhost;database=Chinook;User Id=root;password=P4ssw0rd" providerName="MySql.Data.MySqlClient" /> </connectionStrings>
Start Coding
Ok, we should be ready to start coding our application. Let's create some artists and albums.using (var db = new ChinookContext()) { db.Artists.Add( new Artist { Name = "Anberlin", Albums = { new Album { Title = "Cities" }, new Album { Title = "New Surrender" } } }); db.Artists.Add( new Artist { Name = "The Police", Albums = { new Album { Title = "The Police Greatest Hits" } } }); db.Artists.Add(new Artist { Name = "Avril Lavigne" }); db.SaveChanges(); }Now let's see how to read the data from the database.
using (var db = new ChinookContext()) { var artists = from a in db.Artists where a.Name.StartsWith("A") orderby a.Name select a; foreach (var artist in artists) { Console.WriteLine(artist.Name); } }Finally, here is some code that updates and deletes some data.
using (var db = new ChinookContext()) { var police = db.Artists.Single(a => a.Name == "The Police"); police.Name = "Police, The"; var avril = db.Artists.Single(a => a.Name == "Avril Lavigne"); db.Artists.Remove(avril); db.SaveChanges(); }
4 comments :
to complete this article, the correct connection string with Unicode support is:
Datasource=localhost; Database=testdb; Uid=root; Pwd=123;CHARSET=utf8
and it should be exactly CHARSET (it's case senestive!).
Good Information shared.
Thank you
Thanks for this tutorial, it's the first that seems to work. It works well, but unless I'm doing something wrong, it doesn't create the tables automatically.
I assume this is intentional, but it's a bit confusing at least.
This post is awesome, thourough and makes sense following it. However, I can't make it work.. get an exception that says "Unable to cast object of type 'MySql.Data.MySqlClient.MySqlClientFactory' to type 'System.Data.Entity.Infrastructure.IDbConnectionFactory'"
Can you look into the link below and see if you have $0.02 to add?
http://stackoverflow.com/questions/16410817/entity-framework-5-0-code-first-with-mysql-connector-6-6-5-0-on-net-4-5
Thanks a ton!
- Joao
Post a Comment