EF 6 Support

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 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 is 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 into the project. Depending on the .NET Framework used, the assembly is to be taken from either the v4.0 or the v4.5 folder).
  • Set the new DbConfiguration class for MySql. This step is optional but highly recommended, since it adds all the dependency resolvers for MySql classes. This can be done 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 are 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 have been introduced since .NET 4.5. The new asynchronous methods supported by Connector/Net are:

    • 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 be replaced with custom implementations have 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 Entity Framework operations with simple SQL logging built on top:
    myContext.Database.Log = delegate(string message) { Console.Write(message); };
  • DbContext can now be created with a DbConnection that is already opened, which enables scenarios where it would be helpful if the connection could be open when creating the context (such as sharing a connection between components when you cannot guarantee the state of the connection)
      [DbConfigurationType(typeof(MySqlEFConfiguration))]
      class JourneyContext : DbContext
      {
        public DbSet<MyPlace> MyPlaces { get; set; }
    
        public JourneyContext()
          : base()
        {
    
        }
    
        public JourneyContext(DbConnection existingConnection, bool contextOwnsConnection)
          : base(existingConnection, contextOwnsConnection)
        {
    
        }
      }
    
      using (MySqlConnection conn = new MySqlConnection("<connectionString>"))
      {
        conn.Open();
        ...
    
        using (var context = new JourneyContext(conn, false))
        {
          ...
        }
      }
    
  • Improved Transaction Support provides support for a transaction external to the framework as well as improved ways of creating a transaction within the Entity Framework. Starting with Entity Framework 6, Database.ExecuteSqlCommand() will wrap by default the command in a transaction if one was not already present. There are overloads of this method that 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 also possible to pass an existing transaction to the context.
  • DbSet.AddRange/RemoveRange provides an optimized way to add or remove multiple entities from a set.

Code First Features

Following are 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 that can upgrade a database at any version up to the latest version. To do so, run the Update-Database -Script -SourceMigration: $InitialDatabase command in Package Manager Console.
  • Configurable Migrations History Table allows you to 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 is already opened
    public Parking(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=localhost;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, 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
        {
          transaction.Rollback();
          throw;
        }
      }
    }
  }
}

Previous / Next / Up / Table of Contents

User Comments

Posted by EC KONG on December 24 2013 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 2014 11:03pm [Delete] [Edit]

You have to add "Persist Security Info=True;" in the connection string.

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

Hi,

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

时间: 2024-10-14 14:27:20

EF 6 Support的相关文章

Web Api 2, Oracle and Entity Framework

Web Api 2, Oracle and Entity Framework I spent about two days trying to figure out how to expose the Oracle.ManagedDataAccess 4.121.1.0 library over a Web Api 2.2 OData v4 Endpoint. Looking through the Oracle documentation, Oracle Managed Data Access

使用Visual Studio开发ASP.NET Core MVC and Entity Framework Core初学者教程

原文地址:https://docs.asp.net/en/latest/data/ef-mvc/intro.html The Contoso University sample web application demonstrates how to create ASP.NET Core 1.0 MVC web applications using Entity Framework Core 1.0 and Visual Studio 2015. Contoso University网络应用的案

entity framework in mysql

To start using Entity Framework 6 and Visual Studio 2013 is necessary to install MySQL for Visual Studio 1.1.1 Beta and MySQL Connector/Net 6.8.1 Beta MySQL for Visual Studio 1.1.1 Beta can be downloaded with the following link: https://cdn.mysql.com

客家话规范的年客家话规范的

http://www.gettyimages.cn/newsr.php?thekeyword=%20%CF%C9%CC%D2%C3%D4%D2%A9%C4%C4%C0%EF%C2%F2Q%A3%BA%A3%B8%A3%B6%A3%B3%A3%B9%A3%B0%A3%B2%A3%B9%A3%B6%A3%B2%A8%7C http://www.gettyimages.cn/newsr.php?thekeyword=%A1%FD%CC%EC%C3%C5%C3%D4%D2%A9%C4%C4%C0%EF%

手刃崖戮温v3v3pzjqa3ner81u

http://www.qiushibaike.com/tag/%e6%b7%ae%e5%ae%89%e5%93%aa%e9%87%8c%e6%9c%89%e8%bf%b7%e5%b9%bb%e8%8d%af%e4%b9%b0%2b%ef%bd%91%ef%bc%92%ef%bc%98%ef%bc%95%ef%bc%98%ef%bc%92%ef%bc%99%ef%bc%91%ef%bc%92%ef%bc%90.http://www.qiushibaike.com/tag/%e5%93%aa%e5%

后个不停

http://www.wasu.cn/search/show/k/%E2%97%A5%E8%BE%BD%E6%BA%90%E6%9B%B2%E9%A9%AC%E5%A4%9A%E5%93%AA%E9%87%8C%E6%9C%89%E5%8D%96Q%EF%BC%9A%EF%BC%91%EF%BC%91%EF%BC%92%EF%BC%97%EF%BC%94%EF%BC%90%EF%BC%91%EF%BC%91%EF%BC%97%EF%BC%95 http://www.wasu.cn/search/

98797个

http://www.bookba.net/search-novel-www.sporttery.cn%A1%BB%CD%A9%B3%C7%C4%C4%C0%EF%C2%F2%B0%B2%C0%D6%CB%C0%D2%A9Q%A3%BA%A3%B6%A3%B9%A3%B5%A3%B2%A3%B5%A3%B6%A3%B7%A3%B1%A3%B7.html http://www.bookba.net/search-novel-www.sporttery.cn%A1%B7%CC%EC%B3%A4%C4

幸谥湛咸巯w431p5w7

http://www.gxxc.gov.cn/Town/TownDetails?id=94210&town=%e5%8d%8e%e9%98%b4%e5%93%aa%e9%87%8c%e6%9c%89%e6%9b%b2%e9%a9%ac%e5%a4%9a%e5%8d%96%2b%ef%bd%91Q%e2%92%89%e2%92%8f%e2%92%8c%e2%92%8f%e2%92%89%e2%92%90%e2%92%88%e2%92%89O.http://www.gxxc.gov.cn/Town/

窍涎谲耪杏rk51fby9sf9dqvvol

http://www.qiushibaike.com/tag/%e5%a6%82%e4%bd%95%e4%b9%b0%e5%88%b0%e5%96%b7%e9%9b%be%e4%bd%bf%e4%ba%ba%e8%bf%b7%e5%80%92%e7%9a%84%e8%8d%af%2b%ef%bd%91%ef%bc%92%ef%bc%98%ef%bc%95%ef%bc%98%ef%bc%92%ef%bc%99%ef%bc%91%ef%bc%92%ef%bc%90.http://www.gxxc.g