The Entity Framework 4.0 can now support the MySQL database as well, and this article will show you how to do it in code first.
1. First create a new project, add the following references in the project with NuGet:
2. Add the following configuration to the Web. config file:
1 < connectionStrings > 2 < name= "Mytestcontext" connectionString= "Data source=127.0.0.1;port= 3306;initial catalog=test;user id=root;password=; " ProviderName = "MySql.Data.MySqlClient" /> 3 </ connectionStrings >
3. New Entity class:
Public classUser { Public intId {Get;Set; } [MaxLength ( -)] Public stringUserName {Get;Set; } [MaxLength ( -)] Public stringPassword {Get;Set; } [MaxLength ( -)] Public stringEmail {Get;Set; } }
4. Create the data context for EF, and note that this class inherits DbContext
Public class Efmysqlcontext:dbcontext { public efmysqlcontext () base("name=mytestcontext ") // The name here is the database connection string in Web. config
{ }
Public Get Set ; }
}
Once you have done this, you can call it in the foreground, and if the database test,ef does not exist, the database will be created. The foreground call method is as follows:
var New Efmysqlcontext (); Context. Users.add (new"Wilbur", password="123456 " }); Context. SaveChanges ();
After the program runs, the database is automatically generated:
The DbContext in the Entity framework generates a __migrationhistory table for use with Code frist programming mode.
Well, a simple MySQL EF code first is implemented!
Entity Framework with Mysql code first