0% found this document useful (0 votes)
16 views

using-ef-core-to-query-a-database-slides

Uploaded by

ahmed11611612
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

using-ef-core-to-query-a-database-slides

Uploaded by

ahmed11611612
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Using EF Core to Query a

Database

Julie Lerman
EF Core Expert and Software Coach

@Julielerman | thedatafarm.com
Module Understand EF Core’s query workflow
Overview Basics of querying using EF Core and LINQ
Filtering, sorting, and aggregating in
queries
Explore the SQL queries that EF Core is
building for you
Improve query performance by
deactivating tracking when not needed
Querying Basics
Query Workflow

EF Core reads model,


Express and Sends SQL
works with provider to
execute query to database
work out SQL

context.Authors.ToList() SELECT * from Authors

Adds tracking
Materializes results Receives
details to
as objects tabular results
DbContext instance
The Simplest Query
_context.Authors.ToList()
A LINQ execution method,
e.g., ToList(),
triggers the query to
execute on the database.
Two Ways to Express LINQ Queries

LINQ Methods LINQ Operators

(from a in context.Authors
context.Authors.ToList(); select a)
.ToList()

(from a in context.Authors
context.Authors
where a.FirstName==“Julie”
.Where(a=>a.FirstName==“Julie”)
select a)
.ToList()
.ToList()
More about LINQ Operators
Querying Data in EF Core
Torben Boeck Jensen
var authors = context.Authors.ToList();

var query = context.Authors;


var authors = query.ToList();

Queries are Composable


You don’t need to convey them in a single expression
Triggering Queries via Enumeration

var query=_context.Authors; var query=_context.Authors;

foreach (var a in query) foreach (var a in


{ context.Authors)
Console.Writeline(a.LastName); {
} Console.Writeline(a.LastName);
}
Database connection
remains open during query
enumeration
Enumerate vs. Execute

foreach (var a in context.Authors){ t Good enumeration: Minimal effort on


Console.WriteLine(a.FirstName); enumeration
}

foreach (var a in context.Authors){


RunSomeValidator(a. FirstName);
t Bad enumeration: Lots of work for each result.
CallSomeService(a.Id);
Connection stays open until last result
GetSomeMoreDataBasedOn(a.Id); is fetched.
}

var authors=context.Authors.ToList() t Execution: Smarter to get results first


foreach (var a in authors){
RunSomeValidator(a.FirstName);
CallSomeService(a.Id);
GetSomeMoreDataBasedOn(a.Id);
}
Filtering Queries Securely by Default
Parameterized queries
protect your database from
SQL Injection attacks
More about SQL Injection
Attack Security
Ethical Hacking: SQL Injection
Troy Hunt
EF Core Parameter Creation

Search value is directly in query Search value in a variable


.Where(a=>a.FirstName==“Josie”) var name=“Josie”
.Where(a=>a.FirstName==name)

No parameter is created in SQL Parameter is created in SQL


SELECT * FROM Authors @P1=‘Josie’
WHERE Authors.FirstName=‘Josie’ SELECT * FROM Authors
WHERE Authors.FirstName=@P1
Benefiting From Additional Filtering
Features
Filtering Partial Text in Queries

EF.Functions.Like LINQ Contains

EF.Functions.Like(property, %abc%) property.Contains(abc)

_context.Authors.Where(a=> _context.Authors.Where(a=>

EF.Functions.Like(a.Name,“%abc%”) a.Name.Contains(“abc”)

) )

SQL LIKE(%abc%) SQL LIKE(%abc%)


Finding an Entity Using its Key Value

DbSet.Find(keyvalue)

This is the only task that Find can be used for

Not a LINQ method

Executes immediately

If key is found in change tracker, avoids unneeded database query


Skip and Take for Paging

1. Aardvark 11. African Penguin


2. Abyssinian 12. African Tree Toad
3. Adelie Penguin 13. African Wild Dog Get first 10 animals
4. Affenpinscher 14. Ainu Dog Skip(0).Take(10)
5. Afghan Hound 15. Airedale Terrier
6. African Bush Elephant 16. Akbash
Get next 10 animals
7. African Civet 17. Akita
8. African Clawed Frog 18. Alaskan Malamute Skip(10).Take(10)
9. African Forest Elephant 19. Albatross
10. African Palm Civet 20. Aldabra Giant Tortoise
Sorting Data in Queries
Sorting with LINQ

OrderBy(o=>o.Property) ThenBy(o=>o.Property)

OrderByDescending ThenByDescending
(o=>o.Property) (o=>o.Property)
LINQ Methods Can Be Combined

_context.Authors
.Where(a=>a.LastName=="Lerman")
.OrderByDescending(a=>a.FirstName).ToList();
Aggregating Results in Queries
LINQ to Entities Aggregate Execution Methods
First() FirstAsync()
FirstOrDefault() FirstOrDefaultAsync()
Single() SingleAsync()
SingleOrDefault() SingleOrDefaultAsync()
Last() LastAsync()
LastOrDefault() LastOrDefaultAsync()
Count() CountAsync()
LongCount() LongCountAsync()
Min(), Max() MinAsync(), MaxAsync()
Average(), Sum() AverageAsync(), SumAsync()

No Aggregation
ToList() ToListAsync()
AsEnumerable() AsAsyncEnumerable()
Aggregate Method Pointers

First methods return the first of any matches

First/Single/Last will throw if no results are returned

Single methods expect only one match and will throw if there are
none or more than one

FirstOrDefault/SingleOrDefault/LastOrDefault will return a


null if no results are returned

Last methods require query to have an OrderBy() method


otherwise will throw an exception
Enhancing Query Performance When
Tracking Isn’t Needed
Query Workflow

EF Core reads model,


Express and Sends SQL
works with provider to
execute query to database
work out SQL

context.Authors.ToList() SELECT * from Authors

Adds tracking
Materializes results Receives
details to
as objects tabular results
DbContext instance
Change tracking is
expensive.
Most Common Scenario for No Tracking:
Web and Mobile Apps

Response

Request Request
(Get) (Put/Post/Delete)
No Track Queries
and DbContexts
var author = t AsNoTracking() returns a query, not a DbSet
context.Authors.AsNoTracking()
.FirstOrDefault();

protected override void OnConfiguring t All queries for this DbContext will
(DbContextOptionsBuilder optionsBuilder) default to no tracking
{
optionsBuilder Use DbSet.AsTracking() for special queries
.UseSqlServer(myconnectionString) that
need to be tracked
.UseQueryTrackingBehavior
QueryTrackingBehavior.NoTracking);
}
EF Core, with provider’s help, transforms
LINQ queries into SQL
Query execution is triggered with specific
Review methods
Workflow includes sending SQL to database
EF Core materializes database results into
objects
LINQ filter, sorting and aggregating
methods are also translated into SQL
You can improve performance by disabling
the default tracking when not needed
Up Next:

Tracking and Saving Data with EF Core


Resources

Entity Framework Core on GitHub: github.com/dotnet/efcore

EF Core Documentation: learn.microsoft.com/ef/core

Ethical Hacking: SQL Injection (Pluralsight course by Troy Hunt):


app.pluralsight.com/library/courses/ethical-hacking-sql-injection

.NET Docs: Enumerable.FirstOrDefault Method


docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault

You might also like