Introducing Entity Framework Core (Part 3)
Implementing The Interface
To implement the
interface for the Blazor Server implementation, follow these steps:
- First, we need to create a class. Right-click on the MyBlog.Data project, select Add | Class, and name the class MyBlogApiServerSide.cs.
- Open MyBlogApiServerSide.cs and replace the code. We start by adding the namespaces we need and then create a class that implements the ImyBlogApi interface.
- Add a code to MyBlogApiServerSide.cs inside of the class. To retrieve the data, we will implement a DbContext, but instead of adding it directly, we will utilize a DbContextFactory. Using data contexts in a unit of work is advised for Blazor, implying that we should instantiate the data context and subsequently dispose of it for each data access operation we perform.
- Add a code to our MyBlogApiServerSide.cs just under the code we just added in the class.
- Add relevant codes under the code we just added.
- We could have done the same in our API, just having one delete method, but there might be a moment where we want to handle deletions differently depending on the type. In the IMyBlogApi we have different delete methods for each type. In MyBlogApiServerSide add a code beneath the codes we just added.
- Add another code beneath the code we just added.
The BlogPostTag table is
generated automatically because Entity Framework Core has recognized a
many-to-many relationship. Migrations rely on the __EFMigrationsHistory table
to track which migrations have been applied to the table.
Adding The DbContext To
Blazor
We need to add DbContext
to our Blazor project to be able to access the data from Blazor:
- Beneath the MyBlogServerSide node in Solution Explorer, find Dependencies. Right-click on Dependencies and select Add Project reference.
- In the list of projects, check the MyBlog.Data project and click OK. Now we have all the external items in place, including the external NuGet packages and a reference to our MyBlog.Data project.
- In the MyBlogServerSide project, open the Startup.cs file and add the following using statements-
using
Microsoft.EntityFrameworkCore;
using
MyBlog.Data;
using
MyBlog.Data.Interfaces;
using
MyBlogServerSide.Data;
- Add a code to the ConfigureServices method.
- Finally, we need to make sure the database gets created and that the migration (the code that sets up the database) runs. In Startup.cs, edit the Configure method.
Now we can use our API to access the database in our
Blazor Server project.
Conclusion
We have successfully learned about Entity Framework
Core, created a database using SQLite, used migrations to create the database,
and created an API to access the database.
Comments
Post a Comment