It’s been an exciting world working with the latest Microsoft .NET technologies. First, .NET Core 1.0 was officially released, a lightweight multi-platform programming framework that has shown to be versatile for deployment. There is also a new framework that offers a new opt-in (dependency injection) programming model at a much lower processing and memory expense. Finally, a complete rewrite of the Object-Relational Mapper (O/RM) called Entity Framework Core 1.0.
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 a Database First model. Database First means that the wizard-generated code was based on an existing database.
Based on a strong dose of community suggestions, Microsoft’s second released edition included many improvements and also added a new model called Model First, versioned Entity Framework 4.0 to coincide with the release of .NET 4.0. Model First allows the developer to design the models in an Entity Relational Diagram (ERD) and have it create the database tables and the code used to manage the content.
Entity Framework 4.1 added a third Entity Framework programming model, Code First, which drops the Entity Relational Diagram (ERD) that Database First and Model First require. Instead, the model classes written by the developer represent the models and the database can be created based on the model. The Entity Framework 5.0 and 6.0 releases added even more features such as new entity data types and additional APIs for performing CRUD (Create, Read, Update, Delete) operations against the database.
With the release of all these additional APIs, Entity Framework had grown to be a rather large and cumbersome beast. The goal of EF was never to outperform what could be done with the classic ADO.NET Connection, Command, and DataReader objects. Instead, it was created to significantly limit the amount of code needed to interact with the database. Performance with the latest EF versioned 6.x can sometimes be costly because it attempts to track the relationships between the objects using navigation objects. It attempts to perform several operations to the database as a collection of several atomic operations which make it an extremely chatty interface.
EF, like the .NET framework, had grown to be a large beast of database programming tools. However, when EF 7 was first announced, we were informed that only Code First would be included. EF 6.x would and is still being updated and maintained by Microsoft for those still wanting to use the any of the three models – Code First, Database First, and Model First patterns. EF was eventually rebranded with all other new .NET technology to Core 1.0. EF 7 became Entity Framework Core 1.0.
Like ASP.NET Core 1.0, EF Core does not require the application to be based on .NET Core. The application it will support can be written in either the classic .NET Framework or the new .NET Core. You just need to install the proper libraries into the project.
EF Core 1.0 is easily installed 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 SQL Server (of course!), SQLite, Npgsql, MySQL, Pomelo, SQL Server Compact Edition, IBM Data Servers, and DevArt database providers. Oracle support is coming soon as well as in-memory database solutions. Because all of .NET Core, ASP.NET Core, and EF Core are all open source software (OSS), you also have the option to write your own provider. Support for NoSQL databases such as MongoDB, Redis, and Azure Table Storage are high priority features that will be added to a future release of EF Core.
By dropping Database First and Model First with the Entity Data Models, much has been trimmed. As well, development can focus on Code First – a name the EF team hates because it is so misleading.
I created a simple .NET Standard Console Application project. With the Visual Studio .NET or .NET Core project created and the database provider known, you can install the correct database provider under Manage NuGet Packages or via the PowerShell Package Manager Console.
Here I am installing the SQL Server provider with the design tools, which includes the provide shown above it and the Entity Framework Core Relational library as a dependency.
Note how I went to the Browse tab and searched for Microsoft.EntityFrameworkCore.SqlServer. As you can see, Entity Framework Core can work on top of .NET Core or .NET Standard. Fun Fact: It can also work side by side with Entity Framework 5 or 6 if you are in the process of migrating your code to EF Core.
Immediately before installing the libraries, it prompts (warns?) you of all the updates to libraries it will install. Agreeing to this will install the necessary libraries and tools.
A cool helpful feature that is still in Prerelease mode at the time of writing 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 a new database and tables from your classes. 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.
I decide to use the old crappy SQL Server 200 database called Pubs. I choose this database with all its warts simply because it is a simple design that allows me to focus on the EF Core Toolset and not worry about the “cutting edge” database design best practices.
Back at the NuGet Package manager screen, I search for Microsoft.EntityFrameCore.Tools. I must be sure my results include prerelease tools by selecting the highlighted checkbox.
Again, the tools will remind me of all the libraries that will be installed.
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 to reflect the Pubs database. In Visual Studio 2015, I click Tools | NuGet Package Manager | Package Manager Console. This opens a PowerShell console window near the bottom of Visual Studio. Here I type the command:
Scaffold-DbContext “Server=.;Database=pubs;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer
This will not run perfectly. As stated, this old Publishers (pubs) database is not a perfect design. A couple of the tables (dbo.roysched and dbo.discounts) lack primary keys and thus will not be scaffolded out, for example.
However, the remained tables in the pubs database will be defined as separate classes and a pubsContext class which brings everything together will also be created.
The pubsContext class looks a little different than it did when it was defined prior versions. The connection information is added in the overridden OnConfiguring() method instead of the class constructor. As well, this method includes a DbContextOptionsBuilder class as a parameter. Note how we use this class to opt into using SQL Server with the connection string. Yes, as the warning suggests, we really need to store the connection out of the app and not have it hardcoded as it is here.
The overridden OnModelCreating() method is how we 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.
After the Fluent API method, the tables are defined in the context class. This looks the same as it did in EF 5 and EF 6.
For this example, we 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.
Now we can test the model by add an author and displaying the list! Back in Main(), we can add a little code to fire up DBContext object, add a record, and display the listing.
class Program { static void Main() { using (pubsContext db = new pubsContext()) { Console.WriteLine("Here are the authors"); foreach (Authors 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"); } } } }
Running the app displays all authors.
I hope this tutorial has been helpful….and remember, our team is currently using the newest version and can help you move to it when you are ready!