ASP.NET Core: Razor Pages

Database Access Techniques

DRTL

Applications needs a DbContext for database queries. The DbSet property of a DbContext allows for core CRUDing. Extracting data can be done various ways. Extension methods provide a nice shorthand for most situations. LINQ query and method syntax give a full range of query options.

DbContext

Part of the Entity Framework Core, the DbContext class represents a session with a database and provides an API for working with the database.

The DbContext class has methods for Adding, Modifying and Deleting data. For extracting (querying) data, use the DbSet property of DbContext.

Although Adding, Modifying and Deleting can be done directly via the DbContext it is most commonly done in Web Applications via the DbSet class.

Part of the Entity Framework Core, the DbSet class represents a collection for a given entity.

Various DbSet methods can be used to add, modifiy, delete and query the data via manipulation of the entity.

Whether data is manipulated directly with DbContext or via DbSet, in both cases changes are applied through the SaveChanges() method of the DbContext.

Dbset

The DbSet class represents an entity set that can be used for create, read, update, and delete operations.

Core methods of the DbSet class are:

Find(int)
Uses the primary key to find an entity and return it. A null value is returned if no entity found or the entity is not in context.
Update(entity)
Begins tracking the given entity to update with the values provided. No changes applied to the database until the SaveChanges() is called.
Remove(entity)
Begins tracking the given entity to remove it from the database. No changes applied to the database until the SaveChanges() is called.
SaveChanges()
Saves all changes made in this context to the database.

LINQ Extension Methods

LINQ (Language Integrated Query) extension methods cover standard query operations.

List and examples here

First()

FirstOrDefault()

Single()

SingleOrDefault()

ToList()

Count()

Min()

Max()

Last()

LastOrDefault()

Average()

These are derived from Dbset which itself is derived from IQueryable which itself is derived from IEnumerable which is where all these methods can be found.

LINQ Query Syntax

Similar to SQL Query.

For example an SQL WHERE query of:

SQL

... is written as:

LINQ Query Syntax

LINQ Method Syntax

Uses a lambda expressions to define the condition for the query. Shorthand popular for simple queries. Harder to understand for more complex.

The above SQL example would appear as:

LINQ Method Syntax

Resources

Different Ways to Write LINQ Queries

MS Docs on LINQ

Learn Entity Framework Core

Entity Framework Extension Methods