Language-Integrated Query (LINQ) integrates query capabilities directly into the C# language. Having LINQ as a first class citizen in the C# language provides strong type checking and intellisense. LINQ can operate over many types of data including objects, XML, JSON, and databases.

So far we have accessed data through the Entity Framework context using the ToListAsync() or FindAsync() methods of a DbSet. The former returns all records in a table and the other returns a single record by ID.

This lesson covers several approaches where all or a single record by ID are not enough. We start by replacing the FindAsync(ID) call with a LINQ type syntax statement:

Variable = await _context.SomeDbSet.FirstOrDefaultAsync(m => m.ID == id);

The FirstOrDefaultAsync() method returns a single record that matches the lambda expression in the parameter. This is functionally equivalent to FindAsync() since we are matching on the ID. But, we are not limited to ID in this regard and could as easily search by Name.



Open the file Pages/Continents/Detail.cshtml.cs. Change the way a record is retrieved.

Following the example in the narrative, use FirstOrDefaultAsync() and pass in a lambda expression, using m as the lambda parameter.

While this is not a LINQ command, the syntax is more like LINQ. It is built into the EF context.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?