4

I have a class library that offers some reusable sugar for EntityFrameworkCore, and it currently targets netstandard2.0;netstandard2.1.

I have projects that reference this class library, most of which target netcore, but a few of which target net48.

Updating reference to net50 and EFCore 5.0, I discovered that EFCore 5.0 no longer supports targeting netstandard2.0 / net48.

If I wish to have my class library consumed by both net48 and net50, I believe I must either:

  • limit Microsoft.EntityFrameworkCore packages to version prior to 5.0 (version=[3.1.10,5.0)), or
  • create two libraries:
    • one of which targets netstandard2.0 and references EFCore 3.1.10
    • the other targets netstandard2.1 and references EFCore 5.0

Is there a way to have a single library build to netstandard2.0 referencing EFCore 3.1.10, and netstandard2.1 referencing EFCore 5.0.

I assume this is not practical, and the "right" answer is two distinct libraries.

Eric Patrick
  • 2,097
  • 2
  • 20
  • 31

1 Answers1

3

NuGet packaging provides a solution for this situation. (I needed a NuGet 201 course!)

In the event this helps others, in my .csproj, I added:

<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
[...]
<Choose>
  <When Condition=" '$(TargetFramework)' == 'netstandard2.0'">
    <ItemGroup>
      <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.13" />
    </ItemGroup>
  </When>
  <Otherwise>
    <ItemGroup>
      <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.4" />
    </ItemGroup>
  </Otherwise>
</Choose>

which, when packed with dotnet pack myproject.csproj, produces:

<dependencies>
    <group targetFramework=".NETStandard2.0">
        <dependency id="Microsoft.EntityFrameworkCore" version="3.1.13" exclude="Build,Analyzers" />
        [...]
    </group>
    <group targetFramework=".NETStandard2.1">
        <dependency id="Microsoft.EntityFrameworkCore" version="5.0.4" exclude="Build,Analyzers" />
        [...]
    </group>
</dependencies>

When consumed by tests:

  • targeting .net48, the 3.1.13 version is installed
  • targeting .net5.0, the 5.0.4 version is installed

The downsides:

  • Visual Studio's NuGet Manager cannot be used to update conditional versions; you will need to update these sections manually.
  • Tests need to have a similar conditional section

EDIT: I found it convenient to create a "wrapper project" that manages this conditional reference: e.g. I have a MyData project / NuGET package that is a proxy for including EntityFramework. All other projects that need EntityFramework conditionally, simply reference the MyData. That keeps the <Choose> in just 1 project, and all other projects can go about getting latest as always.

Credit to Mark Heath's article

Eric Patrick
  • 2,097
  • 2
  • 20
  • 31