Querying data

If you've ever used Language Integrated Query (LINQ) before, you'll feel right at home with EF Core. The DbSet collection, which we've used to manipulate objects' states, implements the IQueryable interface that defines many querying operators that are later transformed into SQL statements by the database provider you've used. 

For example, the GiveNTake application allows the user to search for products that were published on a specific date. Here is a shortened version of how it is done:

[HttpGet("search/{date:datetime}/{keyword}/")]
public async Task<IActionResult> Search(DateTime date, string keyword)
{
var products = await _context.Products
.Where(p => p.Title.Contains(keyword))
.Where(p => p.PublishDate.Date == date.Date)
.ToListAsync();

// returning a response with the found products
}

The Where operator creates a filter on the IQueryable<Product> that the Products DbSet collection implements. LINQ has a composable and deferred execution model, where each operator adds another layer on the result returned from the previous operator, but the query itself won't be queried unless explicitly told so. Whenever an iteration is made on the result of the query, or when any completion operator is used, the query is executed and the results are returned to the applications. This includes running a foreach statement, using a conversion operator, such as ToListAsync(), or an operator such Count(), which returns the amount of results.

Any input used inside your queries will be wrapped inside an SQL parameter and will not be blindly concatenated to the query. This will ensure that you're more protected from SQL injection attacks.

There are many LINQ operators you can use in your queries—more than this book can cover. However, I summarized some of what I believe are the most useful ones in this table:

Operator  Description
Select         Transforms the input object of the source type to another object of the result type (which can be the same as the source) by running a given selector function.
Where          Filters the dataset by running a provided predicate on each item.
Take Returns the specified number of items from the start of the result set.
Skip Skips the specified number of items from the start of the result set.

GroupBy

Groups the items in the result set by a key that is specified by a provided key selector function.
SingleOrDefault Returns the single item that the query results contains, or the default value if the results are empty. If more than one item exists in the results, an exception will be thrown.
FirstOrDefault Returns the first item from the query results, or the default value if the results are empty. 
Count Returns the amount of items in the query result.

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.126.211