Entity Framework6 Access MySQL

Source: Internet
Author: User
Tags connectionstrings

Install EF6 with pm command first

Install-package EntityFramework

Configuration changes are as follows

<?XML version= "1.0" encoding= "Utf-8"?><Configuration>  <configsections>    < Sectionname= "Dataconfiguration"type= "Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data " />    <!--for more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -    < Sectionname= "EntityFramework"type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=6.0.0.0, culture= Neutral, publickeytoken=b77a5c561934e089 "requirepermission= "false" />  </configsections>  <connectionStrings>    <Addname= "MyDb"ProviderName= "MySql.Data.MySqlClient"connectionString= "SERVER=192.168.0.2;UID=ROOT;PWD=123456;DATABASE=MYDB2;" />  </connectionStrings>  <EntityFrameworkCodeconfigurationtype= "MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">    <defaultconnectionfactorytype= "System.Data.Entity.Infrastructure.SqlConnectionFactory, entityframework" />    <providers>      <providerInvariantName= "MySql.Data.MySqlClient"type= "MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />      <providerInvariantName= "System.Data.SqlClient"type= "System.Data.Entity.SqlServer.SqlProviderServices, entityframework.sqlserver" />    </providers>  </EntityFramework>  <Startup>    <supportedruntimeversion= "v4.0"SKU=". netframework,version=v4.5 " />  </Startup></Configuration>

Database entities and Context definitions

[Dbconfigurationtype (typeof(mysqlefconfiguration))]  Public classParking:dbcontext { PublicDbset<car> Cars {Get;Set; }  PublicParking ():Base("Name=mydb")        {        }        //Constructor to the use of a DbConnection that's already opened         PublicParking (DbConnection existingconnection,BOOLcontextownsconnection):Base(ExistingConnection, contextownsconnection) {}protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {Base.            Onmodelcreating (ModelBuilder); Modelbuilder.entity<Car>().        Maptostoredprocedures (); }    }     Public classCar { Public intCarid {Get;Set; } [MaxLength ( -)]         Public stringModel {Get;Set; }  Public intYear {Get;Set; } [MaxLength ( $)]         Public stringmanufacturer {Get;Set; } }

EF Invocation Example

    Public Static voidefexecuteexample () {//string connectionString = configurationmanager.connectionstrings["MyDB"].            ConnectionString; //using (mysqlconnection connection = new Mysqlconnection (connectionString))//{            //    //Create database if not exists//using (Parking contextdb = new Parking (connection, false))//    {            //contextDB.Database.CreateIfNotExists (); //    }            //connection.            Open (); //    //mysqltransaction transaction = connection.            BeginTransaction (); //Try//    {            //        //DbConnection that's already opened//using (Parking context = new Parking (connection, false))//        {            //            //interception/sql Logging//context.            Database.Log = (String message) = = {Console.WriteLine (message);}; //            //passing an existing transaction to the context//           //context.            Database.usetransaction (transaction); //            //Dbset.addrange//list<car> cars = new list<car> (); //cars.            ADD (new Car {manufacturer = "Nissan", Model = "370Z", year = 2012}); //cars.            ADD (new Car {manufacturer = "Ford", Model = "Mustang", year = 2013}); //cars.            ADD (new Car {manufacturer = "Chevrolet", Model = "Camaro", year = 2012}); //cars.            ADD (new Car {manufacturer = "Dodge", Model = "Charger", year = 2013}); //context.            Cars.addrange (cars); //context.            SaveChanges (); //        }            //        //Transaction.commit (); //    }            //catch (Exception ex)//    {            //Console.WriteLine (ex.            Message); //        //transaction.            Rollback (); //throw; //    }            //}            //Try//{            //Database.setinitializer (New dropcreatedatabaseifmodelchanges<parking> ());            varContext =NewParking (); //    //insert a row of values//context.            Cars.add (new Car {manufacturer = "Nissan", Model = "370Z", year = 2012}); //int result = context.            SaveChanges (); //}            //catch (Exception ex)//{            //Console.WriteLine (ex.            Message); //}Car Car= Context. Cars.first (item = Item). Carid = =1);//Query by ID            varCars = Context. Cars.where (item = Item). Model = ="370Z");//Condition Lookup
      
Cars = Context. Cars.where (item = Item). Year > 2012);
}

MySQL Native access

 Static voidmysqldbtest () {MySql.Data.MySqlClient.MySqlConnection conn; stringmyconnectionstring; myConnectionString= configurationmanager.connectionstrings["myDb"].            ConnectionString; Try{conn=NewMySql.Data.MySqlClient.MySqlConnection (); Conn. ConnectionString=myconnectionstring; Mysqlcommand cmd=Conn.                CreateCommand (); Cmd.commandtype=System.Data.CommandType.Text; Cmd.commandtext="SELECT * from Users"; Conn.                Open (); using(Mysqldatareader reader =cmd. ExecuteReader (commandbehavior.closeconnection)) { while(reader. Read ()) {Console.WriteLine ("id={0},firstname={1},lastname={2}", reader. GetInt32 (0), reader. GetString (1), reader. GetString (2)); }                }            }            Catch(MySql.Data.MySqlClient.MySqlException ex) {Console.WriteLine (ex).            Message); }        }

Entity Framework6 Access MySQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.