Introducing Entity Framework Core (Part 2)
Creating The Database
Context
The Database Context is
the class from which we will access the database. This is how we create one:
- Right-click on the MyBlog.Data project and select Add | Class. Name the class MyBlogDBContext.cs.
- Open the new MyBlogDBContext.cs file and replace the content with a code.
This file contains two
classes- MyBlogDbContext and MyBlogDbContextFactory. MyBlogDbContext serves as
the DbContext for our database, allowing us to interact with it. The second
class, MyBlogDbContextFactory, is intended for setting up our database during
the migration process; it consists of code that executes exclusively when we
are performing migrations, not during production.
Creating A Migration
A migration is a code
snippet used for configuring the database, which encompasses the creation of
the database and the establishment or modification of tables. We can do this
from within Visual Studio:
- Start PowerShell and navigate to our MyBlog.Data folder.
- If this is the first time we start PowerShell, we might need to launch it as an administrator and run the
following command- Set -ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine
- To install the Entity
Framework tools run the following command- dotnet tool install --global
dotnet-ef
- Now it is time to create our migration. A migration contains the differences between the database now and the changes we have done in our model classes and our MyBlogDbContext.
- To create a migration run
the following command- dotnet ef migrations add InitialDatabaseMigration
We can also use the
Package Manager Console inside Visual Studio to do run these commands.
Creating An Interface
As we are presently
utilizing Blazor Server, we have the ability to connect directly to the
database, meaning that the API we are developing will establish a direct link
to the database:
- Right-click in the Interfaces folder and select Add | Class.
- In the list of different templates, select Interface and name it IMyBlogApi.cs.
- Open IMyBlogApi.cs and replace its content with a code.
The interface contains
all the methods we need to get, save, and delete blog posts, tags, and
categories.
Conclusion
Some more steps to create
a database project using Entity Framework are discussed above.
Comments
Post a Comment