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 than data annotation. This allows us to override the “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 that 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 detect invalid data in model properties and provides the error message to the 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 relationship between entities with the 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 a 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 the "Transaction" feature.
- Query: It supports LINQ in retrieving 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, I will first create a console application using the .NET Core Framework. Here, I am using Visual Studio code as IDE and SQL server as Database. Following are the steps to create a console application with Entity Framework Core.
Step 1. Create a 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 that runs the commands on CLI (Command Line Interface). We can also run the "dotnet" command using the 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 programs.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 information like the version of the .NET Core Framework, compilation options, framework details, dependencies, the script for installing front-end dependencies, etc.
Step 2. Added new dependency of Entity Framework Core to Project.json
Entity Framework Core supports various databases 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 the 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 that are specified in the 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 a simple model class to perform the operation; the following is the 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 the example code.
Step 5. Use the 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 the 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 the “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.