In this first installment of the Using Microsoft's Entity Framework series, we will start with the basics.
Entity framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. EF’s main goal is to help developers focus on the business domain, rather than writing database plumbing code (e.g connections, commands, etc, data tables and datasets).
For years, I have worked with classic ADO.NET and have created my own utility libraries to push and pull data from the database. Although this worked flawlessly, writing repetitive data access code got old and boring. EF is also Microsoft’s preferred data access layer with projects moving forward. ADO.NET and LINQ to SQL are not going away anytime soon (there are still a lot of applications that uses these), but both technologies will no longer receive or have little investments from Microsoft.
So, let’s dive in and get started on how to start using entity framework on a project. The latest version of EF (as of this writing) is 6.01.
Install Nuget via Visual Studio Extension Manager
If you have the Nuget package manager already installed in Visual Studio, skip this step otherwise referred to Nuget Package Manager installation instructions.
Installing EF via Nuget
The fastest and easiest way to install entity framework is to download and install it from Nuget. On your project, you may simply right click on References and click on Manage Nuget Packages. Alternatively, you may also use the Package Manager console (Tools -> Library Package Manager -> Package Manager console) to run the EF powershell installation command. To get more help on how to run the package manager console, see Nuget Package Manager Console PowerShell Reference
One key thing to remember is that if your application is targeting to run on .NET 4.0, then the default EF assembly version will be 4.4. Applications running on .NET 4.5 and above will use the default assembly version 5.0.
Visual Studio.NET FrameworkDefault EF versionEF after NUGET
Create A Model Of An Existing Database (Database First Approach)
After EF is installed, some entries will be added on the web.config/app.config file related to Entity Framework. Now that EF is installed, let’s see how we can add a model of an existing database. Note that there is also a Code-First approach where you typically build the database from scratch in C#, but for simplicity’s sake, let’s just start with an existing database.
1. Right click on your project and click on Add New Item
2. Select the ADO.NET Entity Data Model option from the templates list
3. Follow the steps on the Entity Data Model Wizard and specify the connection string to your database
4. Select all database objects you want to include in your model