text
stringlengths
0
13.4k
classes that interact with a database.
Adding a service class that interacts with Entity Framework Core
(and your database) with the singleton lifecycle (or other lifecycles)
can cause problems, because of how Entity Framework Core
manages database connections per request under the hood. To
avoid that, always use the scoped lifecycle for services that
interact with Entity Framework Core.
The TodoController that depends on an injected ITodoItemService will
be blissfully unaware of the change in services classes, but under the
hood it'll be using Entity Framework Core and talking to a real database!
Test it out
Start up the application and navigate to http://localhost:5000/todo .
The fake items are gone, and your application is making real queries to
the database. There doesn't happen to be any saved to-do items, so it's
59
Create a new service class
blank for now.
In the next chapter, you'll add more features to the application, starting
with the ability to create new to-do items.
60
Add more features
Add more features
Now that you've connected to a database using Entity Framework Core,
you're ready to add some more features to the application. First, you'll
make it possible to add new to-do items using a form.
61
Add new to-do items
Add new to-do items
The user will add new to-do items with a simple form below the list:
Adding this feature requires a few steps:
Adding a form to the view
Creating a new action on the controller to handle the form
Adding code to the service layer to update the database
Add a form
The Views/Todo/Index.cshtml view has a placeholder for the Add Item
form:
<div class="panel-footer add-item-form">
<!-- TODO: Add item form -->
</div>
To keep things separate and organized, you'll create the form as a partial
view. A partial view is a small piece of a larger view that lives in a
separate file.
Create an AddItemPartial.cshtml view:
Views/Todo/AddItemPartial.cshtml
62
Add new to-do items
@model TodoItem
<form asp-action="AddItem" method="POST">
<label asp-for="Title">Add a new item:</label>
<input asp-for="Title">