Introduction
Entity Framework Core is a lightweight and extensible version of Entity Framework. It is based on ORM (Object-Relational Mapper) which enables us to work with databases using .NET objects.
Feature of Entity Framework core
The following features are supported by Entity Framework Core.
- Modelling
- Fluent API
This allows us to configure our domain classes. It provides more functionality for configuration as compared to Data Annotation. This allows us to override “OnModelCreating” method of the context class to configure the model.
- Data annotations
These are attributes that can be added to the entity classes to configure the model classes.
- Shadow properties
Shadow Properties are properties which are not present in our entity model class. The values can be changed and maintained by the Change Tracker API. They can also participate in LINQ to Entity query, database migration, and Create/Update operations.
- Alternate keys
These can be used as a target of the relationship.
- Model validation
It helps us in detecting invalid data into model properties and provides the error message to user.
- Entity / Table splitting
Entity splitting gives us the ability to take an entity in our model and split that into multiple database tables. Table splitting gives us the ability to map multiple entities to a single database table. Table splitting gives us the ability to map multiple entities to a single database table. Table splitting is just the opposite of entity splitting. In other words, two or more entities of our model are mapped to the same physical database table.
- It maintains the relation between entities with help of navigation and foreign key properties
- Change Tracking
It includes many change tracking methods like Snapshot change tracking and Notification change tracking. We can also access the tracked state of entities via DbContext.Entry and DbContext.ChangeTracker. It has also introduced new API "DbContext.AttachGraph" which helps us re-attach entities to a context, in order to save new/modified entities.
- SaveChanges
This version of the EF supports basic save functionality with async support. It also supports Optimistic Concurrency to protect against overwriting changes made by other users. It provides the API to support "Transaction" feature.
- Query
It supports LINQ to retrieve the data from the database. It supports the "NoTracking" feature which enables faster query execution because at this time, context is not required to monitor changes made in entities. This version also supports "Eager loading" and "Lazy Loading".
- Database provides support
This version of the entity framework supports the following database provider.
- SQL Server
- SQL Lite
- Postres
- SQL Compact
- Oracle (Coming Soon)
Hello World Example with Entity Framework Core
In this example, first, I will create console application using .NET Core Framework. Here, I am using Visual Studio code as IDE and SQL server as Database. Following are the steps to create console application with Entity Framework Core.
Step 1 Create new dot net core application
Using the following command, we can create a new .NET Core application. It can be either Web or desktop. The "dotnet" is a general driver to run the commands on CLI (Command Line Interface). We can also run "dotnet" command, using command prompt.
>dotnet new
When we run the command, shown above, it creates an empty project. The empty project mainly contains two files, which are program.cs and project.json.
Program.cs file has a default method called "Main". This method is an entry point for the application. The Project.json file contains the information like version of .NET Core Framework, compilation options, framework details, dependencies, script for installing front-end dependencies etc.
Step 2 Added new dependency of Entity Framework Core to Project.json
Entity Framework Core supports various database like MS SQL server, SQL Lite etc. The.NET core has a built-in provider for MS SQL Server. This provider allows us to query the database. The following two namespaces are required to inject into project.json file to use Entity Framework Core in the application.
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.SqlServer.Design
Project.json
- {
- "version": "1.0.0-*",
- "buildOptions": {
- "debugType": "portable",
- "emitEntryPoint": true
- },
- "dependencies": {},
- "frameworks": {
- "netcoreapp1.0": {
- "dependencies": {
- "Microsoft.NETCore.App": {
- "type": "platform",
- "version": "1.0.1"
- },
- "Microsoft.EntityFrameworkCore.SqlServer" : "1.0.0-rc2-final",
- "Microsoft.EntityFrameworkCore.SqlServer.Design" : "1.0.0-rc2-final"
- },
- "imports": [
- "dnxcore50",
- "portable-net452+win81"
- ]
- }
- }
- }
Step 3 Restore the dependency
Using the following command, we can download/restore all dependencies of the project. It uses NuGet to restore dependencies which are specified in project.json file. Dependencies restorations are done in parallel.
>dotnet restore
Step 4 Create Entity context and Model classes
In this example, I have used simple model class to perform the operation; following is model class and entity context definition.
Entity TestTable
- namespace ConsoleApplication
- {
- public class TestTable
- {
- public int Id { get; set; }
- public string Name { get; set; }
- }
- }
Entity context EntityModelContext
- using Microsoft.EntityFrameworkCore;
- namespace ConsoleApplication
- {
- public class EntityModelContext : DbContext
- {
-
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- optionsBuilder.UseSqlServer(@"Server=(local);Database=TestDB;user Id=sa; password=Passwd@12;");
- }
-
- public DbSet<TestTable> TestTables { get; set; }
-
- }
- }
I have added these classes under the Model folder in example code.
Step 5 Use Entity context class to retrieve the data
This is the final step. Here, I have created the object of the context class and retrieved the TestTable data to list variables and print on screen.
- using System;
- using System.Linq;
-
- namespace ConsoleApplication
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- using(EntityModelContext context = new EntityModelContext())
- {
- var data = context.TestTables.ToList();
- foreach(var d in data)
- {
- Console.WriteLine("{0}\t{1}", d.Id,d.Name);
- }
- }
- }
- }
- }
Output
I have run this application using “dotnet run” command from the command prompt, however we can also run this application using VS code IDE.
Conclusion
Entity Framework is a lightweight version of Microsoft Entity Framework. The EF Core also works with multiple platforms like Windows, Linux or iOS. The EF core contains most of the features of EF 6.x and the Microsoft team is working on introducing new features with EF Core.