Entity Framework Core Flashcards
Entity Framework Core
Entity Framework Core is the new version of Entity Framework after EF 6.x. It is open-source, lightweight, extensible and a cross-platform version of Entity Framework data access technology.
Entity Framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.
EF Core is intended to be used with .NET Core applications. However, it can also be used with standard .NET 4.5+ framework based applications.
EF Core Development Approaches
EF Core supports two development approaches 1) Code-First 2) Database-First. EF Core mainly targets the code-first approach and provides little support for the database-first approach because the visual designer or wizard for DB model is not supported as of EF Core 2.0.
In the code-first approach, EF Core API creates the database and tables using migration based on the conventions and configuration provided in your domain classes. This approach is useful in Domain Driven Design (DDD).
In the database-first approach, EF Core API creates the domain and context classes based on your existing database using EF Core commands. This has limited support in EF Core as it does not support visual designer or wizard.
EF Core Database Providers
Entity Framework Core uses a provider model to access many different databases. EF Core includes providers as NuGet packages which you need to install.
The following table lists database providers and NuGet packages for EF Core.
Database NuGet Package
SQL Server Microsoft.EntityFrameworkCore.SqlServer
MySQL MySql.Data.EntityFrameworkCore
PostgreSQL Npgsql.EntityFrameworkCore.PostgreSQL
SQLite Microsoft.EntityFrameworkCore.SQLite
SQL Compact EntityFrameworkCore.SqlServerCompact40
In-memory Microsoft.EntityFrameworkCore.InMemory
Install Entity Framework Core
Entity Framework Core can be used with .NET Core or .NET 4.6 based applications. Here, you will learn to install and use Entity Framework Core 2.0 in .NET Core applications using Visual Studio 2017.
EF Core is not a part of .NET Core and standard .NET framework. It is available as a NuGet package. You need to install NuGet packages for the following two things to use EF Core in your application:
EF Core DB provider
EF Core tools
for sql server
Microsoft.EntityFrameworkCore.SqlServer(make sure that it has the .NET symbol and the Author is Microsoft)
Notice that the provider NuGet package also installed other dependent packages such as Microsoft.EntityFrameworkCore.Relational and System.Data.SqlClient.
Alternatively, you can also install provider’s NuGet package using Package Manager Console. Go to Tools -> NuGet Package Manager -> Package Manager Console and execute the following command to install SQL Server provider package:
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install EF Core Tools
Along with the DB provider package, you also need to install EF tools to execute EF Core commands. These make it easier to perform several EF Core-related tasks in your project at design time, such as migrations, scaffolding, etc.
EF Tools are available as NuGet packages. You can install NuGet package for EF tools depending on where you want to execute commands: either using Package Manager Console (PowerShell version of EF Core commands) or using dotnet CLI.
Install EF Core Tools for PMC
In order to execute EF Core commands from Package Manager Console, search for the Microsoft.EntityFrameworkCore.Tools package from NuGet UI
This will allow you to execute EF Core commands for scaffolding, migration etc. directly from Package Manager Console (PMC) within Visual Studio.
to execute EF Core commands from .NET Core’s CLI
Install EF Core Tools for dotnet CLI
If you want to execute EF Core commands from .NET Core’s CLI (Command Line Interface), first install the NuGet package Microsoft.EntityFrameworkCore.Tools.DotNet using NuGet UI.
After installing Microsoft.EntityFrameworkCore.Tools.DotNet package, edit the .csproj file by right clicking on the project in the Solution Explorer and select Edit .csproj. Add node as shown below. This is an extra step you need to perform in order to execute EF Core 2.0 commands from dotnet CLI in VS2017.
Exe netcoreapp2.0
Now, open the command prompt (or terminal) from the root folder of your project and execute EF Core commands from CLI starting with dotnet ef
Creating a Model for an Existing Database in Entity Framework Core
Here you will learn how to create the context and entity classes for an existing database in Entity Framework Core. Creating entity & context classes for an existing database is called Database-First approach.
EF Core does not support visual designer for DB model and wizard to create the entity and context classes similar to EF 6. So, we need to do reverse engineering using the Scaffold-DbContext command. This reverse engineering command creates entity and context classes (by deriving DbContext) based on the schema of the existing database.
Scaffold-DbContext Command
Use Scaffold-DbContext to create a model based on your existing database. The following parameters can be specified with Scaffold-DbContext in Package Manager Console:
Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>]
[-DataAnnotations] [-Force] [-Project] [-StartupProject] []
In Visual Studio, select menu Tools -> NuGet Package Manger -> Package Manger Console and run the following command:
PM> Scaffold-DbContext “Server=.\SQLExpress;Database=SchoolDB;
Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Model
In the above command, the first parameter is a connection string which includes three parts: DB Server, database name and security info. Here, Server=.\SQLExpress; refers to local SQLEXPRESS database server. Database=SchoolDB; specifies the database name “SchoolDB” for which we are going to create classes. Trusted_Connection=True; specifies the Windows authentication. It will use Windows credentials to connect to the SQL Server. The second parameter is the provider name. We use provider for the SQL Server, so it is Microsoft.EntityFrameworkCore.SqlServer. The -OutputDir parameter specifies the directory where we want to generate all the classes which is the Models folder in this case.
The above Scaffold-DbContext command creates entity classes for each table in the SchoolDB database and context class (by deriving DbContext) with Fluent API configurations for all the entities in the Models folder.
get-help scaffold-dbcontext –detailed
Use the following command to get the detailed help on Scaffold-DbContext command:
PM> get-help scaffold-dbcontext –detailed
The following is the generated Student entity class for the Student table.
using System;
using System.Collections.Generic;
namespace EFCoreTutorials.Models { public partial class Student { public Student() { StudentCourse = new HashSet(); }
public int StudentId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int? StandardId { get; set; }
public Standard Standard { get; set; } public StudentAddress StudentAddress { get; set; } public ICollection StudentCourse { get; set; } } } The following is the SchoolDBContext class which you can use to save or retrieve data.
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace EFCoreTutorials.Models { public partial class SchoolDBContext : DbContext { public virtual DbSet Course { get; set; } public virtual DbSet Standard { get; set; } public virtual DbSet Student { get; set; } public virtual DbSet StudentAddress { get; set; } public virtual DbSet StudentCourse { get; set; } public virtual DbSet Teacher { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code
. See http://go.microsoft.com/fwlink/?
LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(@”Server=.\SQLExpress
;Database=SchoolDB;Trusted_Connection=True;”);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(entity => { entity.Property(e => e.CourseName) .HasMaxLength(50) .IsUnicode(false); entity.HasOne(d => d.Teacher) .WithMany(p => p.Course) .HasForeignKey(d => d.TeacherId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_Course_Teacher"); }); modelBuilder.Entity(entity => { entity.Property(e => e.Description) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.StandardName) .HasMaxLength(50) .IsUnicode(false); }); modelBuilder.Entity(entity => { entity.Property(e => e.StudentId).HasColumnName("StudentID"); entity.Property(e => e.FirstName) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.LastName) .HasMaxLength(50) .IsUnicode(false); entity.HasOne(d => d.Standard) .WithMany(p => p.Student) .HasForeignKey(d => d.StandardId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_Student_Standard"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e.StudentId); entity.Property(e => e.StudentId) .HasColumnName("StudentID") .ValueGeneratedNever(); entity.Property(e => e.Address1) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Address2) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.City) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.State) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.HasOne(d => d.Student) .WithOne(p => p.StudentAddress) .HasForeignKey(d => d.StudentId) .HasConstraintName("FK_StudentAddress_Student"); }); modelBuilder.Entity(entity => { entity.HasKey(e => new { e.StudentId, e.CourseId }); entity.HasOne(d => d.Course) .WithMany(p => p.StudentCourse) .HasForeignKey(d => d.CourseId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_StudentCourse_Course"); entity.HasOne(d => d.Student) .WithMany(p => p.StudentCourse) .HasForeignKey(d => d.StudentId) .HasConstraintName("FK_StudentCourse_Student"); }); modelBuilder.Entity(entity => { entity.Property(e => e.StandardId).HasDefaultValueSql("((0))"); entity.Property(e => e.TeacherName) .HasMaxLength(50) .IsUnicode(false); entity.HasOne(d => d.Standard) .WithMany(p => p.Teacher) .HasForeignKey(d => d.StandardId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_Teacher_Standard"); }); } } }
EF Core creates entity classes only for tables and not for StoredProcedures or Views.
EF Core creates entity classes only for tables and not for StoredProcedures or Views.
dotnet ef dbcontext scaffold
DotNet CLI
If you use dotnet command line interface to execute EF Core commands then open command prompt and navigate to the root folder and execute the following dotnet ef dbcontext scaffold command:
dotnet ef dbcontext scaffold “Server=.\SQLEXPRESS;Database=SchoolDB;
Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -o Models
use the Migration commands whenever you change the model
Once you have created the model, you must use the Migration commands whenever you change the model to keep the database up to date with the model.
Configuring a DbContext
https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext
Entity Framework Core: DbContext
The DbContext class is an integral part of Entity Framework. An instance of DbContext represents a session with the database which can be used to query and save instances of your entities to a database. DbContext is a combination of the Unit Of Work and Repository patterns.
DbContext in EF Core allows us to perform following tasks
Manage database connection Configure model & relationship Querying database Saving data to the database Configure change tracking Caching Transaction managemen
To use DbContext in our application
To use DbContext in our application, we need to create the class that derives from DbContext, also known as context class. This context class typically includes DbSet properties for each entity in the model. Consider the following example of context class in EF Core.
public class SchoolContext : DbContext { public SchoolContext() {
} protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { }
protected override void OnModelCreating(ModelBuilder modelBuilder) { } //entities public DbSet Students { get; set; } public DbSet Courses { get; set; } } In the example above, the SchoolContext class is derived from the DbContext class and contains the DbSet properties of Student and Course type. It also overrides the OnConfiguring and OnModelCreating methods. We must create an instance of SchoolContext to connect to the database and save or retrieve Student or Course data.
OnConfiguring() method
The OnConfiguring() method allows us to select and configure the data source to be used with a context using DbContextOptionsBuilder. Learn how to configure a DbContext class at here.
OnModelCreating() method
The OnModelCreating() method allows us to configure the model using ModelBuilder Fluent API.
DbContext Methods
Method Usage
Add Adds a new entity to DbContext with Added state and starts tracking it. This new entity data will be inserted into the database when SaveChanges() is called.
AddAsync Asynchronous method for adding a new entity to DbContext with Added state and starts tracking it. This new entity data will be inserted into the database when SaveChangesAsync() is called.
AddRange Adds a collection of new entities to DbContext with Added state and starts tracking it. This new entity data will be inserted into the database when SaveChanges() is called.
AddRangeAsync Asynchronous method for adding a collection of new entities which will be saved on SaveChangesAsync().
Attach Attaches a new or existing entity to DbContext with Unchanged state and starts tracking it.
AttachRange Attaches a collection of new or existing entities to DbContext with Unchanged state and starts tracking it.
Entry Gets an EntityEntry for the given entity. The entry provides access to change tracking information and operations for the entity.
Find Finds an entity with the given primary key values.
FindAsync Asynchronous method for finding an entity with the given primary key values.
Remove Sets Deleted state to the specified entity which will delete the data when SaveChanges() is called.
RemoveRange Sets Deleted state to a collection of entities which will delete the data in a single DB round trip when SaveChanges() is called.
SaveChanges Execute INSERT, UPDATE or DELETE command to the database for the entities with Added, Modified or Deleted state.
SaveChangesAsync Asynchronous method of SaveChanges()
Set Creates a DbSet that can be used to query and save instances of TEntity.
Update Attaches disconnected entity with Modified state and start tracking it. The data will be saved when SaveChagnes() is called.
UpdateRange Attaches a collection of disconnected entities with Modified state and start tracking it. The data will be saved when SaveChagnes() is called.
OnConfiguring Override this method to configure the database (and other options) to be used for this context. This method is called for each instance of the context that is created.
OnModelCreating Override this method to further configure the model that was discovered by convention from the entity types exposed in DbSet properties on your derived context.
DbContext Properties
Method Usage
ChangeTracker Provides access to information and operations for entity instances this context is tracking.
Database Provides access to database related information and operations for this context.
Model Returns the metadata about the shape of entities, the relationships between them, and how they map to the database.
Creating the Model
Entity Framework needs to have a model (Entity Data Model) to communicate with the underlying database. It builds a model based on the shape of your domain classes, the Data Annotations and Fluent API configurations.
The EF model includes three parts: conceptual model, storage model, and mapping between the conceptual and storage models. In the code-first approach, EF builds the conceptual model based on your domain classes (entity classes), the context class and configurations. EF Core builds the storage model and mappings based on the provider you use. For example, the storage model will be different for the SQL Server compared with DB2.
EF uses this model for CRUD (Create, Read, Update, Delete) operations to the underlying database.
Code first appraoch -create entity classes and context classes first
public class Student { public int StudentId { get; set; } public string Name { get; set; } }
public class Course { public int CourseId { get; set; } public string CourseName { get; set; } } Now, we need to create a context class by deriving the DbContext, as shown in the previous chapter. The following SchoolContext class is also called context class.
namespace EFCoreTutorials { public class SchoolContext : DbContext { public DbSet Students { get; set; } public DbSet Courses { get; set; }
protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@" Server=.\SQLEXPRESS ;Database=SchoolDB;Trusted_Connection=True;"); } } }
The above context class includes two DbSet properties, for Student and Course, type which will be mapped to the Students and Courses tables in the underlying database. In the OnConfiguring() method, an instance of DbContextOptionsBuilder is used to specify which database to use. We have installed MS SQL Server provider, which has added the extension method UseSqlServer on DbContextOptionsBuilder.
The connection string “Server=.\SQLEXPRESS;Database=SchoolDB;
Trusted_Connection=True;” in the UseSqlServer method provides database information: Server= specifies the DB Server to use, Database= specifies the name of the database to create and Trusted_Connection=True specifies the Windows authentication mode. EF Core will use this connection string to create a database when we run the migration.
After creating the context and entity classes, it’s time to add the migration to create a database.
“Server=.\SQLEXPRESS;Database=SchoolDB;
Trusted_Connection=True;”
Trusted_Connection=True specifies the Windows authentication mode
After creating the context and entity classes, it’s time to add the migration to create a database.
After creating the context and entity classes, it’s time to add the migration to create a database.
Adding a Migration = to create database from the code first approach
EF Core includes different migration commands to create or update the database based on the model. At this point, there is no SchoolDB database. So, we need to create the database from the model (entities and context) by adding a migration.
We can execute the migration command using NuGet Package Manger Console as well as dotnet CLI (command line interface).
In Visual Studio, open NuGet Package Manager Console from Tools -> NuGet Package Manager -> Package Manager Console and enter the following command:
PM> add-migration CreateSchoolDB
If you use dotnet CLI, enter the following command.
> dotnet ef migrations add CreateSchoolDB
This will create a new folder named Migrations in the project and create the ModelSnapshot files, as shown below.
After creating a migration, we still need to create the database using the update-database command in the Package Manager Console, as below.
PM> update-database –verbose
Enter the following command in dotnet CLI.
> dotnet ef database update
This will create the database with the name and location specified in the connection string in the UseSqlServer() method. It creates a table for each DbSet property (Students and Courses) as shown below.
This was the first migration to create a database. Now, whenever we add or update domain classes or configurations, we need to sync the database with the model using add-migration and update-database commands.
whenever we add or update domain classes or configurations, we need to sync the database with the model using add-migration and update-database commands.
This was the first migration to create a database. Now, whenever we add or update domain classes or configurations, we need to sync the database with the model using add-migration and update-database commands.
Reading or Writing Data
Now, we can use the context class to save and retrieve data, as shown below.
namespace EFCoreTutorials { class Program { static void Main(string[] args) { using (var context = new SchoolContext()) {
var std = new Student() { Name = "Bill" };
context.Students.Add(std); context.SaveChanges(); } } } }
Querying in Entity Framework Core
Querying in Entity Framework Core remains the same as in EF 6.x, with more optimized SQL queries and the ability to include C#/VB.NET functions into LINQ-to-Entities queries.
C#/VB.NET Functions in Queries
EF Core has a new feature in LINQ-to-Entities where we can include C# or VB.NET functions in the query. This was not possible in EF 6.
private static void Main(string[] args)
{
var context = new SchoolContext();
var studentsWithSameName = context.Students
.Where(s => s.FirstName == GetName())
.ToList();
}
public static string GetName() {
return “Bill”;
}
In the above L2E query, we have included the GetName() C# function in the Where clause. This will execute the following query in the database:
exec sp_executesql N’SELECT [s].[StudentId], [s].[DoB], [s].[FirstName],
[s].[GradeId], [s].[LastName], [s].[MiddleName]
FROM [Students] AS [s]
WHERE [s].[FirstName] = @__GetName_0’,N’@__GetName_0 nvarchar(4000)’,
@__GetName_0=N’Bill’
Go
Eager Loading with Include
Entity Framework Core supports eager loading of related entities, same as EF 6, using the Include() extension method and projection query. In addition to this, it also provides the ThenInclude() extension method to load multiple levels of related entities. (EF 6 does not support the ThenInclude() method.)
Unlike EF 6, we can specify a lambda expression as a parameter in the Include() method to specify a navigation property as shown below.
var context = new SchoolContext();
var studentWithGrade = context.Students
.Where(s => s.FirstName == “Bill”)
.Include(s => s.Grade)
.FirstOrDefault();
In the above example, .Include(s => s.Grade) passes the lambda expression s => s.Grade to specify a reference property to be loaded with Student entity data from the database in a single SQL query. The above query executes the following SQL query in the database.
SELECT TOP(1) [s].[StudentId], [s].[DoB], [s].[FirstName], [s].[GradeId],[s].[LastName],
[s].[MiddleName], [s.Grade].[GradeId], [s.Grade].[GradeName], [s.Grade].[Section]
FROM [Students] AS [s]
LEFT JOIN [Grades] AS [s.Grade] ON [s].[GradeId] = [s.Grade].[GradeId]
WHERE [s].[FirstName] = N’Bill’
Include() method, same as in EF 6 - Not recommended using lambda instead
We can also specify property name as a string in the Include() method, same as in EF 6.
var context = new SchoolContext();
var studentWithGrade = context.Students
.Where(s => s.FirstName == “Bill”)
.Include(“Grade”)
.FirstOrDefault();
The example above is not recommended because it will throw a runtime exception if a property name is misspelled or does not exist. Always use the Include() method with a lambda expression, so that the error can be detected during compile time.
Include from sql
The Include() extension method can also be used after the FromSql() method, as shown below.
var context = new SchoolContext();
var studentWithGrade = context.Students
.FromSql(“Select * from Students where FirstName =’Bill’”)
.Include(s => s.Grade)
.FirstOrDefault();
Include() extension method cannot be used after the DbSet.Find()
The Include() extension method cannot be used after the DbSet.Find() method. E.g. context.Students.Find(1).Include() is not possible in EF Core 2.0. This may be possible in future versions.
Multiple Include
Use the Include() method multiple times to load multiple navigation properties of the same entity. For example, the following code loads Grade and StudentCourses related entities of Student.
var context = new SchoolContext();
var studentWithGrade = context.Students.Where(s => s.FirstName == “Bill”)
.Include(s => s.Grade)
.Include(s => s.StudentCourses)
.FirstOrDefault();
The above query will execute two SQL queries in a single database round trip.
SELECT TOP(1) [s].[StudentId], [s].[DoB], [s].[FirstName], [s].[GradeId], [s].[LastName],
[s].[MiddleName], [s.Grade].[GradeId], [s.Grade].[GradeName], [s.Grade].[Section]
FROM [Students] AS [s]
LEFT JOIN [Grades] AS [s.Grade] ON [s].[GradeId] = [s.Grade].[GradeId]
WHERE [s].[FirstName] = N’Bill’
ORDER BY [s].[StudentId]
Go
SELECT [s.StudentCourses].[StudentId], [s.StudentCourses].[CourseId]
FROM [StudentCourses] AS [s.StudentCourses]
INNER JOIN (
SELECT DISTINCT [t].*
FROM (
SELECT TOP(1) [s0].[StudentId]
FROM [Students] AS [s0]
LEFT JOIN [Grades] AS [s.Grade0] ON [s0].[GradeId] = [s.Grade0].[GradeId]
WHERE [s0].[FirstName] = N’Bill’
ORDER BY [s0].[StudentId]
) AS [t]
) AS [t0] ON [s.StudentCourses].[StudentId] = [t0].[StudentId]
ORDER BY [t0].[StudentId]
Go
ThenInclude
EF Core introduced the new ThenInclude() extension method to load multiple levels of related entities. Consider the following example:
var context = new SchoolContext();
var student = context.Students.Where(s => s.FirstName == “Bill”)
.Include(s => s.Grade)
.ThenInclude(g => g.Teachers)
.FirstOrDefault();
In the above example, .Include(s => s.Grade) will load the Grade reference navigation property of the Student entity. .ThenInclude(g => g.Teachers) will load the Teacher collection property of the Grade entity. The ThenInclude method must be called after the Include method. The above will execute the following SQL queries in the database.
SELECT TOP(1) [s].[StudentId], [s].[DoB], [s].[FirstName], [s].[GradeId], [s].[LastName],
[s].[MiddleName], [s.Grade].[GradeId], [s.Grade].[GradeName], [s.Grade].[Section]
FROM [Students] AS [s]
LEFT JOIN [Grades] AS [s.Grade] ON [s].[GradeId] = [s.Grade].[GradeId]
WHERE [s].[FirstName] = N’Bill’
ORDER BY [s.Grade].[GradeId]
Go
SELECT [s.Grade.Teachers].[TeacherId], [s.Grade.Teachers].[GradeId], [s.Grade.Teachers].[Name]
FROM [Teachers] AS [s.Grade.Teachers]
INNER JOIN (
SELECT DISTINCT [t].*
FROM (
SELECT TOP(1) [s.Grade0].[GradeId]
FROM [Students] AS [s0]
LEFT JOIN [Grades] AS [s.Grade0] ON [s0].[GradeId] = [s.Grade0].[GradeId]
WHERE [s0].[FirstName] = N’Bill’
ORDER BY [s.Grade0].[GradeId]
) AS [t]
) AS [t0] ON [s.Grade.Teachers].[GradeId] = [t0].[GradeId]
ORDER BY [t0].[GradeId]
go
Projection Query
We can also load multiple related entities by using the projection query instead of Include() or ThenInclude() methods. The following example demonstrates the projection query to load the Student, Grade, and Teacher entities.
var context = new SchoolContext();
var stud = context.Students.Where(s => s.FirstName == “Bill”)
.Select(s => new
{
Student = s,
Grade = s.Grade,
GradeTeachers = s.Grade.Teachers
})
.FirstOrDefault();
In the above example, the .Select extension method is used to include the Student, Grade and Teacher entities in the result. This will execute the same SQL query as the above ThenInclude() method.
Lazy Loading
Lazy loading is not supported in Entity Framework Core 2.0. Track lazy loading issue on github.
Explicit Loading
Explicit loading works the same way as in EF 6. Learn about it here.
Here you will learn how to load related entities in an entity graph explicitly. Explicit loading is valid in EF 6 and EF Core both.
Even with lazy loading disabled (in EF 6), it is still possible to lazily load related entities, but it must be done with an explicit call. Use the Load() method to load related entities explicitly. Consider the following example.
using (var context = new SchoolContext())
{
var student = context.Students
.Where(s => s.FirstName == “Bill”)
.FirstOrDefault();
context.Entry(student).Reference(s => s.StudentAddress).Load(); // loads StudentAddress context.Entry(student).Collection(s => s.StudentCourses).Load(); // loads Courses collection }
In the above example, context.Entry(student).Reference(s => s.StudentAddress).Load() loads the StudentAddress entity. The Reference() method is used to get an object of the specified reference navigation property and the Load() method loads it explicitly.
In the same way, context.Entry(student).Collection(s => s.Courses).Load() loads the collection navigation property Courses of the Student entity. The Collection() method gets an object that represents the collection navigation property.
The Load() method executes the SQL query in the database to get the data and fill up the specified reference or collection property in the memory, as shown below.
Query()
You can also write LINQ-to-Entities queries to filter the related data before loading. The Query() method enables us to write further LINQ queries for the related entities to filter out related data.
using (var context = new SchoolContext())
{
var student = context.Students
.Where(s => s.FirstName == “Bill”)
.FirstOrDefault();
context.Entry(student) .Collection(s => s.StudentCourses) .Query() .Where(sc => sc.CourseName == "Maths") .FirstOrDefault(); } In the above example, .Collection(s => s.StudentCourses).Query() allows us to write further queries for the StudentCourses entity.
Entity Framework Core: Saving Data in Connected Scenario
Entity Framework Core provides different ways to add, update, or delete data in the underlying database. An entity contains data in its scalar property will be either inserted or updated or deleted based on its EntityState.
There are two scenarios to save an entity data: connected and disconnected. In the connected scenario, the same instance of DbContext is used in retrieving and saving entities, whereas this is different in the disconnected scenario. In this chapter, you will learn about saving data in the connected scenario.
As per the above figure, Entity Framework builds and executes INSERT, UPDATE, or DELETE statements for the entities whose EntityState is Added, Modified, or Deleted when the DbContext.SaveChanges() method is called. In the connected scenario, an instance of DbContext keeps track of all the entities and so it automatically sets an appropriate EntityState of each entity whenever an entity is created, modified, or deleted.