Exploring Entity Framework Core 5
- .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. “
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.
Something To Remember
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
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.”
.NET — A Unified Platform
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.
After Installing The SDK Verify The Version
Top Line Looks Like This: C:\>dotnet –info
It’s time to create a simple.NET 5 Entity Framework application!
First Things First: Create a .NET 5 Console Application
Start By Creating A New Project.
After naming the project, click the Create button.
How To Configure The Project To .NET 5.0 Instead Of .NET 3.1
The solution and its project created above will appear in Visual Studio 2019.
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.
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.”
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…
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.
Click OK after reviewing the list.
Next… Let’s Search For Entity Framework
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
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
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).
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();
}
}
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.
}
}
– Davin Mickelson
Let Intertech Help You Pivot To The New EF Core
Take a look at the proposed .NET Schedule .
.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!