【问题标题】:How to Use Entity Framework 6.x in Asp.Net 5 (MVC 6)如何在 Asp.Net 5 (MVC 6) 中使用实体框架 6.x
【发布时间】:2015-05-31 12:13:00
【问题描述】:

我正在使用 VS 2015 CTP-6 测试新的 Asp.Net 5。由于 Entity Framework 7 中缺少功能,我现在更喜欢使用 EF6。

我已尝试删除 EF7,然后在 PM 中应用 EF6,如下所示:

Uninstall-Package EntityFramework
Install-Package EntityFramework -version 6.1.3

没有返回错误,并且 project.json 文件似乎相应更新。虽然,没有可用的 DbContext。

这有可能吗?如果是,我应该如何从这里开始?我是否需要 web.config 才能与 EF6 兼容?

【问题讨论】:

    标签: c# entity-framework-6 asp.net-core asp.net-core-mvc


    【解决方案1】:

    是的,这很好。

    创建上下文时需要手动设置连接字符串,因为无法从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());
    

    【讨论】:

    • 我们还需要在项目中包含 System.Data 吗?这也会进入依赖关系吗?
    • 您不需要设置依赖项,但由于 .net 核心不支持 EF 6,您需要确保您的框架在project.son.
    • 正如 kenstone 所回答的,在 RC 中应该使用 ConfigurationBuilder,而不是 Configuration。 stackoverflow.com/a/33834167/3805983
    • 看起来不错,但如何使用 MyContext?
    • 只需将它添加到你需要它的控制器的构造函数中:public IActionResult MyController(MyContext context)
    【解决方案2】:

    根据使用的数据库,它可能不像回答那么容易。如果您使用的是 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 AND system.data 部分。这可以通过使用System.Data.Entity.DbConfiguration.Loaded 事件来完成。 Oracle 也是如此。

    查看详细解释的这篇博文:http://bleedingnedge.com/2015/11/01/entity-framework-6-with-asp-net-5/

    【讨论】:

    • 我有一个 "无法确定类型为“MySql.Data.MySqlClient.MySqlClientFactory”的提供程序工厂的提供程序名称。确保在应用程序配置。” MySQL 异常。为了使它工作,我在 DbConfiguration 类中添加了更多设置:SetProviderFactory("MySql.Data.MySqlClient", new MySql.Data.MySqlClient.MySqlClientFactory()); SetProviderFactoryResolver(new MySql.Data.Entity.MySqlProviderFactoryResolver());
    【解决方案3】:

    您不能只在 startup.cs 文件中执行此操作吗?保存创建工厂

    // new context on each request
    services.AddScoped<IMyContext, MyContext>((s) =>
    {
        return new MyContext(Configuration["Data:MyConnection:ConnectionString"]);
    });
    

    【讨论】:

    • 甚至在 1 行中:services.AddScoped(s => new MyContext(Configuration["Data:MyConnection:ConnectionString"]));
    【解决方案4】:

    在 RC 版本中,这变成:

            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables();
            var Configuration = builder.Build();
            var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
    

    【讨论】:

      【解决方案5】:

      ‌开始之前,请确保在 project.json 中针对完整的 .NET Framework 进行编译,因为 Entity Framework 6 不支持 .NET Core。如果您需要跨平台功能,则需要升级到 Entity Framework Core。

      在您的 project.json 文件中为完整的 .NET Framework 指定一个目标:

      "frameworks": {
          "net46": {}
      }
      

      然后设置连接字符串和依赖注入

      public class ApplicationDbContext : DbContext
      {
          public ApplicationDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
          {
          }
      }
      

      在 ConfigureServices 的 Startup 类中,添加上下文的工厂方法及其连接字符串。上下文应在每个范围内解析一次,以确保性能并确保实体框架的可靠运行。

      public void ConfigureServices(IServiceCollection services)
      {
          services.AddScoped((_) => new ApplicationDbContext(Configuration["Data:DefaultConnection:ConnectionString"]));
      
          // Configure remaining services
      }
      

      ntity Framework 6 允许在 xml(在 web.config 或 app.config 中)或通过代码指定配置。从 ASP.NET Core 开始,所有配置都是基于代码的。

      基于代码的配置是通过创建System.Data.Entity.Config.DbConfiguration 的子类并将System.Data.Entity.DbConfigurationTypeAttribute 应用到您的DbContext 子类来实现的。

      我们的配置文件通常如下所示:

      <entityFramework>
          <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
              <parameters>
                  <parameter value="mssqllocaldb" />
              </parameters>
          </defaultConnectionFactory>
          <providers>
              <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
          </providers>
      </entityFramework>
      

      defaultConnectionFactory 元素设置连接的工厂。如果未设置此属性,则默认值为 SqlConnectionProvider。另一方面,如果提供了值,则给定类将用于使用其 CreateConnection 方法创建 DbConnection。如果给定的工厂没有默认构造函数,那么您必须添加用于构造对象的参数

      [DbConfigurationType(typeof(CodeConfig))] // point to the class that inherit from DbConfiguration
      public class ApplicationDbContext : DbContext
      {
          [...]
      }
      
      public class CodeConfig : DbConfiguration
      {
          public CodeConfig()
          {
              SetProviderServices("System.Data.SqlClient",
                  System.Data.Entity.SqlServer.SqlProviderServices.Instance);
          }
      }
      

      本文将向您展示如何在 ASP.NET Core 应用程序中使用 Entity Framework 6。 https://docs.asp.net/en/latest/data/entity-framework-6.html

      【讨论】:

        猜你喜欢
        • 2013-12-17
        • 1970-01-01
        • 1970-01-01
        • 2015-01-10
        • 1970-01-01
        • 2015-05-20
        • 1970-01-01
        • 2016-07-11
        • 1970-01-01
        相关资源
        最近更新 更多