EF 6 Support

Source: Internet
Author: User
Tags connectionstrings

MySQL Connector/net 6.8 integrates support for Entity Framework 6.0 (EF 6), but also offers support for Entity Framework 5 . This section explains the new features in the Entity Framework 6 implemented in Connector/net 6.8.

Requirements for Entity Framework 6.0 support
    • MySQL connector/net 6.8.x

    • MySQL Server 5.1 or above

    • Entity Framework 6 Assemblies

    • . NET Framework 4.0 or above

Configurations

Configure connector/net to support EF 6 by the following steps:

  • An important first step was editing the configuration sections in the App.cofig file to add the connection string and the MySQL Connector/net Provider for EF 6:

      <connectionStrings>    <add name= "mycontext" providername= "MySql.Data.MySqlClient" connectionstring= " Server=localhost;      port=3306;database=mycontext;uid=root;password=******** "/>  </connectionStrings>  < 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>

  • Add the reference for MYSQL.DATA.ENTITY.EF6 assembly to the project. Depending on the. NET Framework used, the assembly are to being taken from either the v4.0 or the v4.5 folder).

  • Set the new Dbconfiguration class for MySql. This step was optional but highly recommended, since it adds all the dependency resolvers for MySql classes. T His can-do in three ways:

      • Adding the dbconfigurationtypeattribute on the context class:

        [Dbconfigurationtype (typeof (Mysqlefconfiguration))]

      • Calling dbconfiguration.setconfiguration (New Mysqlefconfiguration ()) at the application startup

      • Set the dbconfiguration type in the configuration file:

        <entityframework codeconfigurationtype= "MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6" >

    It is also possible to create a custom dbconfiguration class and add the dependency resolvers needed.

EF 6 Features

Following is the new features in Entity Framework 6 implemented in MySQL connector/net 6.8:

  • Async Query and Save adds support for the task-based asynchronous patterns that has been introduced since. NET 4 .5. The new asynchronous methods supported by Connector/net is:

    • Executenonqueryasync

    • Executescalarasync

    • Prepareasync

  • Connection resiliency/retry Logic enables automatic recovery from transient Connection failures. To use this feature, add to the Oncreatemodel Method:

    Setexecutionstrategy (Mysqlproviderinvariantname.providername, () = new Mysqlexecutionstrategy ());

  • code-based configuration gives you the option of performing Configuration in Code, instead of performing it in a Configuration file, as it has been-done traditionally.

  • Dependency Resolution introduces support for the Service Locator. Some pieces of functionality that can is replaced with custom implementations has been factored out. To add a dependency resolver, use:

    Adddependencyresolver (New Mysqldependencyresolver ());

    The following resolvers can be added:

    • DbProviderFactory-Mysqlclientfactory

    • idbconnectionfactory-Mysqlconnectionfactory

    • Migrationsqlgenerator-Mysqlmigrationsqlgenerator

    • dbproviderservices-Mysqlproviderservices

    • Iproviderinvariantname-Mysqlproviderinvariantname

    • Idbproviderfactoryresolver-Mysqlproviderfactoryresolver

    • Imanifesttokenresolver-Mysqlmanifesttokenresolver

    • Idbmodelcachekey-Mysqlmodelcachekeyfactory

    • Idbexecutionstrategy-Mysqlexecutionstrategy

  • interception/sql Logging provides low-level building blocks for interception of the Entity Framework operations with Simple SQL logging built on top:

    MyContext.Database.Log = delegate (String message) {console.write (message);};

  • DbContext can now being created with a DbConnection so is already opene D , which enables scenarios where it would be helpful if the connection could is open when creating the context (such As sharing a connection between components if you cannot guarantee the state of the connection)

     [Dbconfigurationtype (typeof (Mysqlefconfiguration))] class Journeycontext:dbcontext {public DbSet& Lt     Myplace> myplaces {get; set;} Public Journeycontext (): Base () {} public Journeycontext (DbConnection existingconnection, BOOL Contextow Nsconnection): Base (ExistingConnection, Contextownsconnection) {}} using (Mysqlconnection conn = new MYSQ Lconnection ("<connectionString>")) {Conn.    Open ();  ... using (var context = new Journeycontext (conn, false)) {...} } 

     

  • Improved Transaction Support provides-a Transaction external to the framework as well as improved- s of creating a transaction within the Entity Framework. Starting with Entity Framework 6, would Database.ExecuteSqlCommand() wrap by default the command in a transaction if one is not already present. There is overloads of this method, the Allow users to override this behavior if wished. Execution of stored procedures included in the model through APIs such as ObjectContext.ExecuteFunction() does the same. It is a existing transaction to the context of also possible to pass.

  • Dbset.addrange/removerange provides an optimized-to-add or remove multiple entities from a set.

Code First Features

Following is new Code first features supported by Connector/net:

    • Code First Mapping to insert/update/delete Stored procedures Supported:

      Modelbuilder.entity<entitytype> (). Maptostoredprocedures ();

    • idempotent migrations Scripts allow you to generate a SQL script the can upgrade a database at any version up to The latest version. To doing so, run the update-database-script-sourcemigration: $InitialDatabase command in package Manager Conso Le.

    • Configurable Migrations History table allows your customize the definition of the Migrations History table.

Example for Using EF 6

Model:

Using mysql.data.entity;using system.data.common;using System.Data.Entity; namespace ef6{  //code-based Configuration and Dependency resolution  [Dbconfigurationtype (typeof ( Mysqlefconfiguration)] public  class Parking:dbcontext  {public    dbset<car> Cars {get; set;}     Public Parking ()      : Base ()    {     }     //Constructor to use on a DbConnection that's already opened public    P Arking (DbConnection existingconnection, bool contextownsconnection)      : Base (ExistingConnection, Contextownsconnection)    {     }     protected override void Onmodelcreating (Dbmodelbuilder modelBuilder)    {      base. Onmodelcreating (ModelBuilder);      Modelbuilder.entity<car> (). Maptostoredprocedures ();    }  }   public class Car  {public    int Carid {get; set;}     public string Model {get; set;}     public int year {get; set;}     public string manufacturer {get; set;}}  }

Program:

Using mysql.data.mysqlclient;using system;using System.Collections.Generic; Namespace Ef6{class Example {public static void Executeexample () {String connectionString = "Server=localh       Ost;port=3305;database=parking;uid=root; ";        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 is already opened using (Parking context = new Parking (connection, FAL SE)) {//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 {transaction.          Rollback ();        Throw }      }    }  }}

Previous/next/up/table of Contents

User Comments
Posted by EC KONG on December 4:05am [Delete] [Edit]

Is this example support connection string with password? I tried and got this inner exception "innerexception = {" Authentication to host ' localhost ' for user ' root ' using method ' Mysql_native_password ' failed with message:access denied for user ' root ' @ ' localhost ' (using Password:no) "}"

Posted by ROBERTO RUIZ DEL VALLE on February 8 11:03pm [Delete] [Edit]

You have to add "Persist Security info=true;" In the connection string.

Posted by Roberto Ezequiel Garcia Ballesteros on February 5:04pm [Delete] [Edit]

Hi

Sure, you can change the connection string according your configuration (add password, change database, etc). This is a example.

EF 6 Support

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.