MySQL is installed, and today we are talking about how to use EntityFramework's codefirst to create a database in a MySQL database
Target framework:. NET Framework 4
The first step: Create a new project and add the following references, which can be added in NuGet or downloaded to the official website and added
Step Two: to add a database node configuration in a configuration file
<span style= "font-family:arial;font-size:10px;" ><?xml version= "1.0"?><configuration> <startup> <supportedruntime version= "v4.0" Sku= ". netframework,version=v4.0 "/> </startup> <connectionStrings> <add name=" Conncodefirst "connectionstring=" Server=192.168.24.184;port=3306;uid=root;pwd=123456;database=code "ProviderName = "MySql.Data.MySqlClient"/> </connectionStrings></configuration></span>
Step Three:We write entity classes
<span style= "font-family:arial;font-size:10px;" >using system;using system.collections.generic;using system.componentmodel.dataannotations;using System.Linq; Using System.text;namespace codefirst4{ //Customer class public class customer { [Key] //customer ID Public String ID {get; set;} Customer Name Public string Cusname {get; set;}}} </span>
Fourth Step:writing a database context
<span style= "font-family:arial;font-size:10px;" >using system;using system.collections.generic;using system.data.entity;using System.Linq;using System.Text; namespace codefirst4{ //Database context public class Hoteldbcontext:dbcontext {public hoteldbcontext () : Base ("Name=conncodefirst") { } public dbset<customer> customer {get; set;}}} </span>
Fifth Step:Write CREATE DATABASE code
<span style= "font-family:arial;font-size:10px;" >using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace codefirst4{ class program { static void Main (string[] args) { Hoteldbcontext dbCOntext = new Hoteldbcontext (); BOOL Flag=dbcontext.database.createifnotexists (); if (flag==true) { Console.WriteLine ("MySQL Database created successfully! "); } else { Console.WriteLine ("MySQL Database creation failed! "); } } }} </span>
Through the simple communication above, I think everyone should understand how to use Codefirst to create a MySQL database, when we started to learn EF, we are in the SQL Server database mapping, then the MySQL database and SQL Server database where the difference? 1th: The reference is different, MySQL needs to refer to Mysql.data; 2nd: The database node configuration in the configuration file is different. In addition to the above two points, other places are similar.
C # EF codefirst create MySQL Database