我如何在ASP.NET 5中使用Entity Framework 6与MySQL?

3

我有一个现有的网站,使用ASP.NET MVC 4,Entity Framework 6和MySQL。我想升级到ASP.NET 5,但希望继续使用Entity Framework 6,因为Entity Framework缺少一些功能,而且还不支持MySQL。如何在ASP.NET 5中使用EF6?

1个回答

3

由于ASP.NET 5不再使用Web.config,因此您需要使用基于代码的配置(code-based configuration)来进行配置。为此,请创建一个继承自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());
    }
}

配置的第一部分是在运行时动态地向system.data部分添加一个新的配置项,以此来注册ADO.NET提供程序。这种做法有些取巧,但似乎能够正确地工作。
将连接字符串添加到config.json而不是Web.config中:
{
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=localhost; Database=test; Uid=test; Pwd=password;"
    }
  }
}

修改 DbContext 以使用正确的配置和连接字符串:

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

Startup.cs中将MyContext注册到依赖注入容器中:

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

然后,你只需使用构造函数注入将 MyContext 传递到您的控制器中即可。
有关更多详细信息,请参见我的博客文章:http://dan.cx/2015/08/entity-framework-6-mysql-aspnet,示例项目请访问https://github.com/Daniel15/EFExample

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接