由于 Web.config 不再与 ASP.NET 5 一起使用,因此您需要使用基于代码的配置 https://msdn.microsoft.com/en-us/data/jj680699.aspx来配置它。为此,创建一个继承自 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());
}
}
配置的第一部分是在运行时注册 ADO.NET 提供程序,方法是动态地将新的配置条目添加到system.data
部分。这是非常hacky的,但看起来确实可以正常工作。
将连接字符串添加到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"])
{
}
// ...
}
登记MyContext
在依赖注入容器中Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddScoped<MyContext>();
}
然后你可以使用构造函数注入来获取MyContext
进入您的控制器。
更多详细信息,请参阅我的博客文章:http://dan.cx/2015/08/entity-framework-6-mysql-aspnet http://dan.cx/2015/08/entity-framework-6-mysql-aspnet,以及一个示例项目https://github.com/Daniel15/EFExample https://github.com/Daniel15/EFExample