使用 ASP.Net Core 2 Web App 使用 EF6 调用 Full 库

Using an ASP.Net Core 2 Web App to call Full a library using EF6

我正在尝试从新的 Asp Net Core 2.0 Web 应用程序调用 .Net 4.7 数据访问库(使用 Entity Framework 6)。

问题是 EF6 似乎无法获取 DbProviderFactory。我的工作理论是,这应该在调用程序的 app/web.config 中提供。我得到的错误是:

System.TypeLoadException: 'Could not load type 'System.Data.Common.DbProviderFactories' from assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.'

为了避免这个问题,我创建了一个 DbConfiguration class:

public class MyDbConfiguration : DbConfiguration
{
    public MyDbConfiguration()
    {
        SetProviderFactory("System.Data.SqlClient", System.Data.SqlClient.SqlClientFactory.Instance);
        SetProviderServices("System.Data.SqlClient", SqlProviderServices.Instance);

    }
}

[DbConfigurationType(typeof(MyDbConfiguration))]
public class MyDbContext : DbContext, IMyDbContext
{
    public MyDbContext(string connectionString)
        : base(connectionString)
    {


    }

断点显示正确执行了MyDbConfiguration,但仍然报错。我已经在 .Net Core 网络应用程序上安装了 System.Data.SqlClient 和 System.Data.Common 包。

我还没有发现任何明确说明我正在尝试做的事情(通常)是不可能的,所以我假设我的 DBConfiguration 实现有问题。请问有人能给我指出正确的方向吗?

如果您想使用来自 .Net Core 应用程序的 Entity Framework 库,您应该 re-target 针对 .Net Framework 的应用程序。这是引自 official source:

To use Entity Framework 6, your project has to compile against .NET Framework, as Entity Framework 6 doesn't support .NET Core. If you need cross-platform features you will need to upgrade to Entity Framework Core.

如果您检查使用 EF6 库的 .Net .Core 项目示例(linked 来自同一文档)(正是您的情况),您会发现它针对的是 .Net Framework,而不是 .Net核心:

<TargetFramework>net452</TargetFramework>

进行此类重定向时,您不会丢失当前正在使用的任何 .Net Core 功能。您仍然可以在 .Net Core 中使用我们喜欢的所有好东西。但是,您将可以启动应用程序的平台限制为仅限 .Net Framework。不幸的是,您目前无法解决此限制,因为 Entity Framework 仅针对 .Net Framework 实现。您的选择要么转向 Entity Framework 核心,要么等到 .Net Standard 的 Entity Framework will become the part

总之,要解决您当前的问题,请更改 .Net Core csproj 文件中的以下行:

<TargetFramework>netcoreapp2.0</TargetFramework>

<TargetFramework>net47</TargetFramework>