Introduction To Entity Framework Core

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.

  1. Microsoft.EntityFrameworkCore.SqlServer  
  2. Microsoft.EntityFrameworkCore.SqlServer.Design  
Project.json
  1. {  
  2.   "version""1.0.0-*",  
  3.   "buildOptions": {  
  4.     "debugType""portable",  
  5.     "emitEntryPoint"true  
  6.   },  
  7.   "dependencies": {},  
  8.   "frameworks": {  
  9.     "netcoreapp1.0": {  
  10.       "dependencies": {  
  11.         "Microsoft.NETCore.App": {  
  12.           "type""platform",  
  13.           "version""1.0.1"  
  14.         },  
  15.         "Microsoft.EntityFrameworkCore.SqlServer" : "1.0.0-rc2-final",  
  16.         "Microsoft.EntityFrameworkCore.SqlServer.Design" : "1.0.0-rc2-final"  
  17.       },  
  18.       "imports": [  
  19.         "dnxcore50",  
  20.         "portable-net452+win81"  
  21.       ]  
  22.     }  
  23.   }  
  24. }  
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
  1. namespace ConsoleApplication  
  2. {  
  3.     public class TestTable  
  4.     {  
  5.         public int Id { get; set; }  
  6.         public string Name { get; set; }  
  7.     }  
  8. }  
Entity context EntityModelContext
  1. using Microsoft.EntityFrameworkCore;  
  2. namespace ConsoleApplication  
  3. {  
  4.     public class EntityModelContext : DbContext  
  5.     {  
  6.           
  7.             protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  8.             {  
  9.                 optionsBuilder.UseSqlServer(@"Server=(local);Database=TestDB;user Id=sa; password=Passwd@12;");  
  10.             }  
  11.   
  12.             public DbSet<TestTable> TestTables { get; set; }  
  13.   
  14.     }  
  15. }  
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.
  1. using System;  
  2. using System.Linq;  
  3.   
  4. namespace ConsoleApplication  
  5. {  
  6.     public class Program  
  7.     {  
  8.         public static void Main(string[] args)  
  9.         {  
  10.             using(EntityModelContext context = new EntityModelContext())  
  11.             {  
  12.                 var data = context.TestTables.ToList();  
  13.                 foreach(var d in data)  
  14.                 {  
  15.                     Console.WriteLine("{0}\t{1}", d.Id,d.Name);  
  16.                 }  
  17.             }  
  18.         }  
  19.     }  
  20. }  
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.

Up Next
    Ebook Download
    View all
    Learn
    View all