How to use Entity Framework 6 with MySQL in ASP.NET 5?

I have an existing site that uses ASP.NET MVC 4, Entity Framework 6 and MySQL. I am trying to upgrade it to ASP.NET 5 but want to continue using Entity Framework 6 as some features are missing from Entity Framework and MySQL is not supported yet. How do I use EF6 in ASP.NET 5?

+3


source to share


1 answer


Since Web.config is no longer used with ASP.NET 5, you need to use Code Based Configuration to set it up. To do this, create a new class that inherits from DbConfiguration:

public class MyDbConfiguration : DbConfiguration
{
    public MyDbConfiguration()
    {
        // Register ADO.NET provider
        var dataSet = (DataSet)ConfigurationManager.GetSection("system.data");
        dataSet.Tables[0].Rows.Add(
            "MySQL Data Provider",
            ".Net Framework Data Provider for MySQL",
            "MySql.Data.MySqlClient",
            typeof(MySqlClientFactory).AssemblyQualifiedName
        );

        // Register Entity Framework provider
        SetProviderServices("MySql.Data.MySqlClient", new MySqlProviderServices());
        SetDefaultConnectionFactory(new MySqlConnectionFactory());
    }
}

      

The first part of the configuration is a hack to register an ADO.NET provider at runtime by dynamically adding a new configuration entry to the section system.data

. This is very dangerous but seems to be working correctly.

Add your connection string to config.json

, not Web.config

:

{
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=localhost; Database=test; Uid=test; Pwd=password;"
    }
  }
}

      

Modify DbContext

to use the correct configuration and connection string:



[DbConfigurationType(typeof(MyDbConfiguration))]
public class MyContext : DbContext
{
    public MyContext(IConfiguration config)
      : base(config["Data:DefaultConnection:ConnectionString"])
      {
      }
      // ...
}

      

Register MyContext

dependency injection in the container in Startup.cs

:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddScoped<MyContext>();
}

      

Then you can just use constructor injection to get MyContext

in your controllers.

More details in my blog post http://dan.cx/2015/08/entity-framework-6-mysql-aspnet and sample project https://github.com/Daniel15/EFExample

+2


source







All Articles