ENTITY FRAMEWORK CORE

CREATE LINQ QUERIES

NET CORE

Linq is the other technology we will use to query the database and get back course information. Linq does not send SQL queries, we have actual C# methods that will allow us to select, filter, sort data. Linq allows us to query any data source.

Linq
Linq_2

Let’s look at the interface IEnumerable<T>.

IEnumerable

The minimum requirement for using Linq is that the class implements sequential access with IEnumerable<T>. Let’s start with Where, which is an Extension Method that can filter a list of items it receives as input. It produces another list that contains either all the elements, some of them or none. This depends on whether these elements meet a certain criterion; we provide the criterion through lambda expressions.

Where
Where_2

The List<Apple> input is not altered by Where since it is read only sequentially. According to the lambda set in the output only red apples end up. Let’s see how Where and Select work in combination.

Where e Select

The first lambda extracts red apples, the second a collection of red apple weights arriving at Select.

Average

We see the difference on code readability when using Linq.

Leggibilità

START WITH ENTITY FRAMEWORK CORE

It is obtained from NuGet as a package and is also provider-based. Whoever produces the provider must convert Linq queries to the specific database technology. We will be dealing with two classes, DbContext and DbSet. The question marks that remained unknown until now are represented by the class DbSet<T>.

DbSet

The DbSet<T> is a set i.e., a collection of elements that come from a database. T indicates the type of these elements, so if we want to be able to query the courses that we have in the database, we would have a DbSet where Course represents a new class that we are going to create and whose properties represent the columns in the Courses table. DbSet<T> is a connected object, so we can address our Linq queries to it as shown in the image. What EF Core will do is to transform the Linq query into SQL statements.

Pattern Repository

You would think that the moment you invoke the Add or Remove or Delete method EF Core would perform that operation immediately. In reality, as we shall see, this is not the case. Let’s look at the DbContext.

DbContext

Entity classes are part of the so-called conceptual model, which is the set of all these entity classes to which we can address Linq queries. By configuration we mean providing the DbContext with the ConnectionString to connect to the database, with mapping we are going to indicate the properties that each of these entity classes maps to the database tables.

Provider
Scaffold

PRACTICE WITH LINQ

Linq