Examples

.NET Entity Framework Query

Building an EF Core Query

.NET EF Core query retrieves data with LINQ expressions.

Introduction to EF Core Queries

Entity Framework Core (EF Core) is a modern Object-Relational Mapper (ORM) for .NET. It simplifies data access by allowing developers to use LINQ to query databases. This post covers examples of querying data using EF Core and LINQ expressions.

Setting Up the Context

Before you can run queries, you need to set up your DbContext. The DbContext is responsible for managing the database connection and provides methods to query and save data.

Assuming you have a model named Product, here is how you can set up your context:

Simple Query Using LINQ

Once your context is ready, you can execute a simple query to fetch all products from the database. The following example demonstrates how to do this using LINQ:

Filtering Data

EF Core allows you to filter data using LINQ's Where method. Below is an example that retrieves products with a price greater than 100:

Sorting Results

You can also sort the results of your query using the OrderBy and OrderByDescending methods. Here's how to sort products by price in ascending order:

Selecting Specific Columns

Sometimes, you may need only specific columns from the database. You can achieve this using the Select method. Below is an example selecting only the Name and Price of products:

Conclusion

EF Core provides a powerful, flexible way to interact with databases using LINQ. By understanding how to set up your context and execute various queries, you can efficiently retrieve and manipulate data in your applications. Whether you're filtering, sorting, or selecting specific columns, EF Core's capabilities can accommodate a wide range of data operations.