Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Entity Framework 6.3.0 in a .NET Standard 2.0 class library?

Is it possible to use Entity Framework 6.3.0 in a .NET Standard 2.0 class library?

In Dependencies -> Packages I have a reference to Entity Framework 6.3.0

And I have code like this:

using System.Data.Entity;

public partial class AlertContext : DbContext

But I get the following errors:

The type or namespace name 'Entity' does not exist in the namespace 'System.Data' (are you missing an assembly reference?)

The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?)

like image 714
Giuseppe Ranieri Avatar asked Oct 30 '19 13:10

Giuseppe Ranieri


People also ask

Can you use Entity Framework with .NET standard?

NET Framework won't support . NET Standard 2.1 or later versions.

Can we use Entity Framework in class library?

Right click the project > Add Existing Item > Go to the MyEntityModel project and add the App. config file. Explanation: When you create a library and the library is referenced from another project, EF will read the config that is relative to start up project.


1 Answers

6.3.0 was the first version of Entity Framework 6 to target .NET Standard; it targets .NET Standard 2.1 along with .NET 4.0 and .NET 4.5, as can be seen in its Nuget listing. 6.2.0 only targeted .NET.

Note that .NET Standard 2.0 is still not a valid target.

Depending on your scenario, you might be able to get away with multi-targeting your library to .NET (in my example below, .NET 4.7.2) and .NET Standard 2.1:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>   
    <TargetFrameworks>net472;netstandard2.1</TargetFrameworks>
  </PropertyGroup>
</Project>

Whether this is viable depends on 2 factors:

  • Your other references. The combination I offer above will be fine in most cases as .NET 4.7.2 and .NET Standard 2.1 can reference .NET Standard 2.0 packages, which covers most but by no means all modern packages.

  • The frameworks that you wish to consume your library from. The .NET target means, of course, that the library can be consumed by .NET Framework projects of the same .NET version or higher. The .NET Standard 2.1 target allows the library to be consumed by projects targeting .NET Standard 2.1, .NET Core 3.0, Mono 6.4, and higher, plus the latest versions of Xamarin. The notable omission is versions of .NET Core prior to 3.0. EF6 is not available to .NET Core 1 or 2. See the .NET Standard .NET implementation support table for the full list.

* I have used .NET 4.7.2 for my illustration because whilst .NET 4.6.1 officially supports .NET Standard 2.0, Microsoft recommend using 4.7.2 or higher. See my answer here for more information.

like image 153
Stephen Kennedy Avatar answered Oct 17 '22 19:10

Stephen Kennedy