text stringlengths 0 13.4k |
|---|
{ |
return await _context.Items |
.Where(x => x.IsDone == false) |
.ToArrayAsync(); |
} |
} |
} |
57 |
Create a new service class |
You'll notice the same dependency injection pattern here that you saw in |
the MVC basics chapter, except this time it's the ApplicationDbContext |
that's getting injected. The ApplicationDbContext is already being added |
to the service container in the ConfigureServices method, so it's |
available for injection here. |
Let's take a closer look at the code of the GetIncompleteItemsAsync |
method. First, it uses the Items property of the context to access all the |
to-do items in the DbSet : |
var items = await _context.Items |
Then, the Where method is used to filter only the items that are not |
complete: |
.Where(x => x.IsDone == false) |
The Where method is a feature of C# called LINQ (language integrated |
query), which takes inspiration from functional programming and makes |
it easy to express database queries in code. Under the hood, Entity |
Framework Core translates the Where method into a statement like |
SELECT * FROM Items WHERE IsDone = 0 , or an equivalent query document |
in a NoSQL database. |
Finally, the ToArrayAsync method tells Entity Framework Core to get all |
the entities that matched the filter and return them as an array. The |
ToArrayAsync method is asynchronous (it returns a Task ), so it must be |
await ed to get its value. |
To make the method a little shorter, you can remove the intermediate |
items variable and just return the result of the query directly (which |
does the same thing): |
public async Task<TodoItem[]> GetIncompleteItemsAsync() |
58 |
Create a new service class |
{ |
return await _context.Items |
.Where(x => x.IsDone == false) |
.ToArrayAsync(); |
} |
Update the service container |
Because you deleted the FakeTodoItemService class, you'll need to |
update the line in ConfigureServices that is wiring up the |
ITodoItemService interface: |
services.AddScoped<ITodoItemService, TodoItemService>(); |
AddScoped adds your service to the service container using the scoped |
lifecycle. This means that a new instance of the TodoItemService class |
will be created during each web request. This is required for service |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.