我正在测试新的Asp.Net 5,使用VS 2015 CTP-6。由于实体框架7中缺少功能,我现在更喜欢使用EF6。
我尝试删除EF7,然后在PM中应用EF6,如下所示:
Uninstall-Package EntityFramework
Install-Package EntityFramework -version 6.1.3没有返回错误,project.json文件似乎也相应更新。虽然,没有可用的DbContext。
这有可能吗?如果是的话,我该怎么做呢?我需要web.config来实现EF6兼容性吗?
发布于 2015-04-10 23:32:35
是的,这个很好。
创建上下文时需要手动设置连接字符串,因为它无法从web.config获得
所以你可以这么做
public class MyContext : DbContext {
public MyContext(string connectionString) : base(connectionString) {
}
}
var context = new MyContext("myConnectionString");如果要从config.json获取连接字符串,请尝试如下
IConfiguration configuration = new Configuration().AddJsonFile("config.json");
var connectionString = configuration["Data:DefaultConnection:ConnectionString"]);如果您想将上下文注入到DI容器中,那么我添加了这样一个工厂
public static class MyContextFactory
{
public static MyContext GetContext() {
IConfiguration configuration = new Configuration().AddJsonFile("config.json");
return new MyContext(configuration["Data:DefaultConnection:ConnectionString"]);
}
}然后将其添加到startup.cs中
services.AddTransient<MyContext>((a) => MyContextFactory.GetContext());发布于 2015-11-09 14:14:54
取决于所使用的数据库,它可能不像回答的那么简单。如果您使用的是MsSql,那么就不需要配置,所接受的答案也是完全正确的。但是使用LocalDB可能需要一些配置。
例如,MySql需要注册提供程序
[DbConfigurationType(typeof(CodeConfig))] // point to the class that inherit from DbConfiguration
public class ApplicationDbContext : DbContext
{
[...]
}
public class CodeConfig : DbConfiguration
{
public CodeConfig()
{
SetDefaultConnectionFactory(new MySql.Data.Entity.MySqlConnectionFactory());
SetProviderServices("MySql.Data.MySqlClient",
new MySql.Data.MySqlClient.MySqlProviderServices());
}
}PostgreSql需要将提供程序注册到entityFramework和system.data部分。这可以通过使用System.Data.Entity.DbConfiguration.Loaded事件来完成。Oracle也是如此。
查看这篇详细解释它的博客文章:http://bleedingnedge.com/2015/11/01/entity-framework-6-with-asp-net-5/
发布于 2015-10-12 11:25:51
您不能只在startup.cs文件中这样做吗?保存创建工厂
// new context on each request
services.AddScoped<IMyContext, MyContext>((s) =>
{
return new MyContext(Configuration["Data:MyConnection:ConnectionString"]);
});https://stackoverflow.com/questions/29296073
复制相似问题