Exploring Entity Framework Core 5

It’s an exciting time to be working with the latest Microsoft .NET technologies. .NET 5, released on November 10th, 2020, combines several smaller, distinct frameworks together into one grandiose framework that includes:
    • .NET Framework
    • .NET Core
    • Xamarin
    • ASP.NET Core
    • WinForms
    • WPF (Windows Presentation Foundation)
    • UWP (Universal Windows Platform)
    • ML.NET (Machine Learning .NET)
    • and Entity Framework (EF) Core.

In this article we are going to look at Entity Framework (EF) Core 5 and explore how it can be implemented in a .NET solution.

Overview Of Entity Framework (EF) And How We Got Here

“Like other OR/M frameworks, the goal was never to outperform what could be done with the classic fundamental ADO.NET Connection, Command, and DataReader objects. In fact, it’s impossible because Entity Framework is built to use these data access classes. Instead, it was created to significantly reduce the amount of code needed for interacting with a data source. “


Technically, Entity Framework (EF) has already been out for a while. Originally released in 2008 as part of Service Pack 1 for .NET 3.5 and Visual Studio 2008, Entity Framework 1.0 was released with the original “Database First” model. Database First means that the wizard-generated code is based on an existing database. It was Microsoft’s first official attempt to creating an Object/Relational Mapping (O/RM) framework. Java developers had already been successfully using Hibernate since its release in 2001 – something nHibernate was based upon. EF 4.x was later released (no EF2 or EF3) with “Model First” and “Code First.” EF5 and EF6 were later released – all for the .NET Framework.

Like other OR/M frameworks, the goal was never to outperform what could be done with the classic fundamental ADO.NET Connection, Command, and DataReader objects. In fact, it’s impossible because Entity Framework is built to use these data access classes. Instead, it was created to significantly reduce the amount of code needed for interacting with a data source. When EF Core 1.0 was released as part of .NET Core, it was rewritten from scratch so it could be optimized for high performance and simplicity. Since then, additional releases have come out that have further enhanced its capabilities while maintaining great performant. Be aware that team has made breaking changes to EF Core with major releases (especially with EF Core 3+) for performance and capability reasons.

It is easy to get the latest released version of EF from NuGet. Assuming an EF Core provider has been created for your database platform, you must be sure to install the correct version. At the time of writing, EF Core supports Microsoft SQL Server (of course!), SQLite, Npgsql, MySQL, and many other database providers list here. Because .NET Core, ASP.NET Core, and EF Core are all open source software (OSS), you also have the option to write your own provider.

“Because .NET Core, ASP.NET Core, and EF Core are all open source software (OSS), you also have the option to write your own provider.”

Something To Remember

Remember that the pre-Core editions of Entity Framework (5/6 for .NET Framework) still support the two “currently dropped” entity designer models Database First and Model First. By dropping Database First and Model First with the Entity Data Models, much has been trimmed. As well, development is focused on Code First – a name the EF team hates because it is misleading. Existing databases as well as automatically created databases can be used with the Code First model.

EF Core 3+ May Work With Your Existing System


EF Core 3+ will work with .NET Standard 2.1+ applications – specifically .NET Core 2 and newer applications. To be clear, applications do not have to also be developed in .NET 5, although using .NET 5 is recommended for all new projects. You just need to install the proper libraries for your project.

On Release of .NET 5 All “.NET Conf 2020” Presentations Were Published For Viewing

When Microsoft released the RTM versions of .NET 5 and EF Core 5, they held a live three day virtual conference called “.NET Conf” (November 10-12, 2020) at the virtual .NET Conf 2024.

All the 30-minute presentations were recorded and published on the dotNET YouTube channel.

.NET — A Unified Platform

“The power of .NET 5 is that it brings all the disparate development frameworks together under one umbrella .NET Standard framework.”


The power of .NET 5 is that it brings all the disparate development frameworks together under one umbrella .NET Standard framework. Thus, .NET 5 becomes the new .NET Standard for .NET Core, WPF, ASP.NET, Xamarin, Unity, and more.

.NET — A Unified Platform

One breaking change that Microsoft is not proud of is .NET Standard 2.1. When Microsoft moved from .NET Standard 2.0 to 2.1, this version broke the standard away from the classic .NET framework (1.0-4.8) which Microsoft has been supporting since its release in 2002.

Before installing the .NET 5 SDK, I highly recommend you first install Visual Studio 2019. It is available in three (3) editions – Community (free!), Professional, and Enterprise. If you are following along on your own machine, know that Community Edition will offer almost everything you need to develop .NET 5 applications. I am always impressed when the Microsoft developers use the Community edition for their demos at their conferences. Watch for it at .NET Conf events.

Visual Studio is available for Windows and macOS. However, for Linux you will need to rely on the CLI tools and an alternate coding editor such as Visual Studio Code (VS Code). Technically you can use the CLI tools with any of the operating systems. Some developers prefer to use the CLI tools. This example will use Visual Studio. I could have use Visual Studio Code or any other coding editor available for this example. So long as I have the appropriate SDK installed for my platform, I can create, build, publish, and deploy projects using my favorite Command Line Interface (CLI) shell.

I will use Visual Studio 2019.

“This article uses a newly released x64 .NET 5 SDK for Windows version downloaded and installed using the link below.”
As the image above describes, you can download this SDK for the most popular operating systems. You can also download the latest binaries of the framework.

After Installing The SDK Verify The Version

After installing the SDK on my x64 Windows 10 machine, verify the version by opening a VS 2019 Developer Command Prompt (which is installed with Visual Studio 2019) and type: dotnet –info

Top Line Looks Like This: C:\>dotnet –info

As you can see, I have the latest .NET 5 Standard SDK tools installed. It shows the installation path plus all my older .NET Core SDKs. Each one of them is eating up about 500MB. I may have to start uninstalling the older ones!

It’s time to create a simple.NET 5 Entity Framework application!

First Things First: Create a .NET 5 Console Application

First, you need to create a .NET 5 Console application.

Start By Creating A New Project.

Next, configure the project filter types. Set it to C#, for All platforms, and Console application projects. Select the Console App (.NET Core) (not the one for .NET Framework!) and click Next.
Finally, give the project a more meaningful (if not a bit misleading) name, ConsoleAppWithEF5. This app with be created in .NET 5 – not to be confused with the classic EF 5 that was released for the .NET Framework. I suspect the “Core” moniker will go away eventually since .NET 5 is the official .NET Standard.

After naming the project, click the Create button.

The solution and its project will appear in Visual Studio 2019. However, it just be configured. (see below)

How To Configure The Project To .NET 5.0 Instead Of .NET 3.1

Technically, this project is configured as a .NET 3.1 Core application. Visual Studio 2019 Preview does not assume we want to use prerelease frameworks. The .NET 5 RC 2 version (released October 13, 2020) and newer now supports the “Go Live” license, which means it is fully supported by Microsoft when used in production.

Link to announcement.

The solution and its project created above will appear in Visual Studio 2019.

If I select the project and click Show All Files, I can see the .NET Core 3.1 dependency in the \bin\ folder.
In order to set it to .NET 5.0, I need configure the project .csproj file (the hard way by editing it) or by simply changing the version in the project’s properties (the easy way). I suggest the easy way. Editing the .csproj file is harder because it’s easy to misspell the case-sensitive framework version and ultimately break your project.

Instead, right-click the project (not the solution!) in the Solution Explorer window and click Properties. Then change the framework version to 5.0. It should appear if you’ve installed the latest .NET SDK and the updates to Visual Studio 2019.

Don’t forget to click the Save All toolbar button.
Done! You are now using .NET 5.0.

Now… Lets Add EF 5 Core To The Project

“You still need to add EF 5 Core to the project. There are two (2) main libraries that must be added.”


First I must mention that I decided to use one of the older, simpler SQL Server sample databases called Pubs, still available by clicking this link.
“The reason I choose this database because of its simple design and it allows me to focus on the EF Toolset rather than wrestle with the “cutting edge” database features, such as those highlighted in the AdventureWorks2019 or WideWorldImporters databases.”
Note: You can download those databases at the same website mentioned above.

I still need to add EF 5 Core to my project. There are two (2) main libraries that I must add. First, you must install EF CLI tools. Second, you must install my EF provider for the type of database vendor you will be supporting. Understand that when you install these two NuGet packages, they will install several dependent packages. Don’t be intimidated by the number of dependencies!

To get started, you must right-click the project and click Manage NuGet Packages…

At the top, navigate to the Browse tab (don’t miss this step!) and select the Include prerelease checkbox if you like to live dangerously. Enter Microsoft.EntityFrameworkCore.Tools into the search textbox. Note the two dependencies for this package. This version of The Microsoft.EntityFrameworkCore.Design dependency package brings in the Relational dependency package which then brings in the main Microsoft.EntityFrameworkCore dependency package.

You can see the commonly used CLI commands listed in the package’s description. These can be used in your favorite CLI shell or in Visual Studio’s NuGet Package Manager Console (PMC). Select the first package that appears in the results and click the Install button.

When you click Install, you will see the notification of all the packages that will be installed.

Click OK after reviewing the list.

You will then be prompted accept the licenses on the EF packages. Click I Accept after reviewing the list.

Next… Let’s Search For Entity Framework

Next, since you will be using a SQL Server database, search for the Microsoft SQL Server provider for Entity Framework. If you are querying a different vendor’s database, you should install the appropriate package. Before clicking Install, note the dependencies. It includes the SQL Server data provider and (again) the Relational package. After clicking Install, agree to the changes and accept the license agreements.
Go back to the Installed tab and clear the search box. It should show the two (2) installed packages.
Remember – these are the two primary packages you will usually need to install. They include several dependencies that offer most of the capabilities of EF.

One helpful feature of the EF tools is the ability to scaffold out the required classes from an existing database structure. Of course, this feature is entirely optional. You could simply create new classes manually based on your database tables. However, I truly believe one of the easiest ways to learn the code needed to work with Entity Framework Core is to study the code generated for you by the team’s database reverse engineering toolset.

What Is Scaffolding? Scaffolding is the process of generating starter source code based on a model or database.

We Just Installed The EF Core Scaffolding Tools So Now Let’s Use Them Based On The Pubs Database

In Visual Studio, click Tools | NuGet Package Manager | Package Manager Console. This opens a PowerShell console window near the bottom of Visual Studio.

Here you type the command:

Scaffold-DbContext “Server=.;Database=pubs;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer

As shown in the Solution Explorer window, all the pubs database tables are defined as separate classes.

Upon inspection of most of these classes, nothing remarkable should jump out at you, other than possible relationship collections tying them to other classes (one to many, many to one, etc.) For example, the Author class has a “one to many” relationship with the Titleauthor class. The Titleauthor class is a join table that enables a “many to many” relationship between the Author and Title tables. This collection is marked as virtual and will be overridden when necessary by Entity Framework.

View an example below.

An Example Of How It Works

For this example, you will interact with the Authors model. Since there is a “many to many” relationship between authors and titles, a HashSet collection is created and used. This collection includes functions for working with sets such as UnionWith, IntersectWith, and more. It also includes a virtual property to the Titleauthor table that can be overridden.
The class that brings all the classes together and ties in Entity Framework is the pubsContext class.
This class inherits from DbContext, bringing in Entity Framework. When instantiated, DBContextOptions can be passed into the constructor to configure the EF and how it is used. Each DBSet property represents an “in-memory” virtual table that represents the physical table in the database.

The pubsContext class looks a little different than it did when it was defined in prior .NET Framework versions. The connection information is added in the overridden OnConfiguring() method. As well, this method includes a DbContextOptionsBuilder class as a parameter. Note how you use this class to opt into using SQL Server with the connection string. As the warning suggests for use in production, we need to store the connection string outside of the app and not have it hardcoded as shown.

A partial method also exists here called OnModelCreating(). When a method is declared as partial, the compiler will look for a method with the same name in the class – even if it is defined in a partial class distributed across multiple source code files. If it finds the implemented method, it will be compiled into the assembly. If it cannot find a matching method, it will be compiled out of the assembly. As well, any calls to that member of the class will also be compiled out (not included in the build).

Click here for the docs on partial methods.

The implemented method is part of Entity Framework and is using the Fluent API, which is based on the Fluent design pattern. The Fluent pattern is based on method chaining, with each method returning an object and allowing you to immediately use a member of the returned object without temporarily storing it in a variable.
The overridden OnModelCreating() method is how you use the Fluent API. It includes a ModelBuilder parameter for configuring each of the entities. It offers the advantage of having the final say over all class configuration rules while not muddying up the model classes as attribute-based data annotations would do.

The ModelBuilder class acts as a Fluent API. By using it, you can configure many different things, as it provides more configuration options such as business rules and display rules as an alternative to data annotation attributes in the classes. Note in the code above how it specifies the column names in the table, maximum sizes, if they are required, and more.

Try testing the model by displaying the authors. Back in Main(), you can add a little code to fire up our pubsContext object and display the listing. Later, you will add a record and redisplay the list. You put the display code in a separate method so it can be reused.

class Program
{
  static void Main(string[] args)
  {
    using (pubsContext db = new pubsContext())
    {
      DisplayAuthors(db);
    }
  }

  private static void DisplayAuthors(pubsContext db)
  {
    Console.WriteLine("n====================");
    Console.WriteLine("Here are the authors:");
    Console.WriteLine("====================n");
    foreach (Author author in db.Authors)
    {
      Console.WriteLine($"{author.AuFname} {author.AuLname}");
      Console.WriteLine(author.Address);
      Console.WriteLine($"{author.City}, {author.State}  {author.Zip}");
      Console.WriteLine($"Phone: {author.Phone}nContract: {author.Contract}n");
    }

    Console.WriteLine("Press any key to continue...");
    Console.ReadKey();
  }
}
Running the app displays all authors.
Add code to add a new author and then redisplay the list of authors.
static void Main(string[] args)
{
  using (pubsContext db = new pubsContext())
  {
    DisplayAuthors(db);

    Author a = new Author();
    a.AuId = "111-22-3333";
    a.AuLname = "Smith";
    a.AuFname = "John";
    a.Phone = "123 456-7890";
    a.Address = "123 Maple Street";
    a.City = "Eagan";
    a.State = "MN";
    a.Zip = "55122";
    a.Contract = true;

    db.Authors.Add(a); // Add the author.
    db.SaveChanges(); // Commit changes to the database.

    DisplayAuthors(db); // Redisplay the authors.
  }
}
When you rerun the example, you see John Smith has been added as a new author.
I hope this tutorial has been helpful. Best wishes and good luck.

– Davin Mickelson

Let Intertech Help You Pivot To The New EF Core

It’s easy to delay adopting new technologies, even when the stakes are high. In so many cases, the energy is spent improving business strategies (building more widgets, increasing quality, refining services). At the same time, technology updates take a back seat when it comes to corporate reinvestment, even when security is a priority, and using older technology is often the weak link in performance.

 

Take a look at the proposed .NET Schedule .

 

w

.NET 5.0 Support And What You Should Know.

As you can see, Microsoft is changing its release strategy for .NET. After .NET 5.0 is released, they will continue to release a new major version every year in November. Microsoft is also changing its support strategy for .NET with Long Term Support (LTS) versions. Specifically, going forward, even-numbered version releases will be LTS versions with odd-numbered releases being General Availability (GA) releases. This new rapid release schedule can easily be overlooked by teams maintaining software solutions. It’s a significant shift in the release strategy for .NET by Microsoft. Software using the .NET framework will need to be updated to maintain security and performance.

If you are using .NET, speak with Intertech about complete application development & keeping your team up-to-date! Davin Mickelson & Intertech are ready to hear from you!

Discover All That Intertech Can Do For You!

Let’s Build Something Great!

Tell us what you need and we’ll get back with you ASAP!