博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
EF for Mysql
阅读量:6006 次
发布时间:2019-06-20

本文共 7951 字,大约阅读时间需要 26 分钟。

(官方教程:)

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

Configuration

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:

  • 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:

    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
    MyPlaces { get; set; } public JourneyContext() : base() { } public JourneyContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } } using (MySqlConnection conn = new MySqlConnection("
    ")) { 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
    ().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
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
().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
cars = new List
(); 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; } } } }}

转载于:https://www.cnblogs.com/iampkm/p/5082367.html

你可能感兴趣的文章
Windows 8.1 今年 1 月市场份额超 Vista
查看>>
《设计团队协作权威指南》—第1章1.5节总结
查看>>
Chair:支付宝前端团队推出的Node.js Web框架
查看>>
《Total Commander:万能文件管理器》——第3.8节.后续更新
查看>>
BSD vi/vim 命令大全(下)[转]
查看>>
css3中变形与动画(一)
查看>>
[XMove-自主设计的体感解决方案] 系统综述
查看>>
设计模式 ( 十五 ) 中介者模式Mediator(对象行为型)
查看>>
【LINUX学习】磁盘分割之建立primary和logical 分区
查看>>
【YUM】第三方yum源rpmforge
查看>>
IOS(CGGeometry)几何类方法总结
查看>>
才知道系列之GroupOn
查看>>
⑲云上场景:超级减肥王,基于OSS的高效存储实践
查看>>
linux kswapd浅析
查看>>
变更 Linux、Ubuntu 时区、时间
查看>>
高仿QQ空间 侧滑Menu效果且换肤功能《IT蓝豹》
查看>>
mac的git的21个客户端
查看>>
Spring Cloud自定义引导属性源
查看>>
[共通]手机端网页开发问题及解决方法整理
查看>>
我的友情链接
查看>>