Entity Framework Setup - GRAPHQL API IN .NET w/ HOT CHOCOLATE #5.1
Summary
TLDRThis tutorial video script guides viewers through setting up a GraphQL API with Hot Chocolate, focusing on integrating Entity Framework for data access. It covers installing necessary packages, creating DTOs and a DbContext, and configuring a SQLite database. The script also details the process of defining DbSets, applying migrations, and setting up automatic migration application on startup, providing a solid foundation for future GraphQL features like data loaders, pagination, and filtering.
Takeaways
- 🛠️ The video covers the setup of GraphQL operations using Hot Chocolate, focusing on data access services with Entity Framework.
- 📦 It's necessary to install specific packages like 'HotChocolate.Data.EntityType' to integrate with Entity Framework and handle parallel resolver execution.
- 🏢 The creation of a database context and Data Transfer Objects (DTOs) is essential to map GraphQL schema to the database structure.
- 📁 A new folder structure is introduced with 'DTOs' and 'Services' to organize the project better and separate concerns.
- 🔄 The script demonstrates the process of creating a 'SchoolDbContext' and defining 'DbSets' for each DTO to establish database tables.
- 🔗 The importance of establishing relationships, such as many-to-many between courses and students, is highlighted in the DTO setup.
- 📝 The script guides through the migration creation process using Entity Framework Core commands in a .NET environment.
- 🔍 It's crucial to ensure that the database context inherits from the DbContext class to function correctly with Entity Framework.
- 🔄 The video shows troubleshooting steps when migrations fail, such as missing references or incorrect relationships in the schema.
- 🚀 The video concludes with the application of database migrations on startup using the host services in the 'Program.cs' file.
- 📚 The script serves as a prerequisite for further GraphQL and Hot Chocolate exploration in subsequent parts of the series.
Q & A
What is the main focus of the video script?
-The main focus of the video script is to demonstrate how to implement services for data access using Entity Framework in a GraphQL API with Hot Chocolate.
Why is it necessary to install the Hot Chocolate.Data.EntityFramework package?
-The Hot Chocolate.Data.EntityFramework package is necessary because it allows for the execution of resolvers in parallel, which is a feature that is not supported by default in Entity Framework.
What are DTOs and why are they used in this context?
-DTOs (Data Transfer Objects) are used to describe how data will be laid out in the database. They are used in this context to reflect the GraphQL schema and define the structure of data that will be accessed via the database.
What is the purpose of creating a separate folder for DTOs and Services in the project?
-Creating separate folders for DTOs and Services helps in organizing the code better, separating concerns, and making the project structure more maintainable.
Why is it important to define DbSets in the DbContext?
-Defining DbSets in the DbContext is important because it tells Entity Framework which entities should be represented as tables in the database.
What is the significance of moving the Subject enum to a separate layer?
-Moving the Subject enum to a separate layer (models folder) centralizes the definition, making it easier to manage and reuse across different parts of the application, such as DTOs and the GraphQL schema.
Why is it necessary to create migrations for the database?
-Creating migrations is necessary to manage changes in the database schema over time. It allows for the application of these changes in a controlled and reversible manner.
What package is needed to use SQLite with Entity Framework?
-The package needed to use SQLite with Entity Framework is Microsoft.EntityFrameworkCore.Sqlite.
How can migrations be automatically applied on application startup?
-Migrations can be automatically applied on application startup by using the Migrate method on the database within the DbContext during the application's initialization process.
What is the purpose of creating a PooledDbContextFactory?
-Creating a PooledDbContextFactory is used to manage the lifecycle of DbContext instances, allowing for efficient reuse of database connections and improving performance.
How is the connection string for the database typically configured?
-The connection string for the database is typically configured in the appsettings.json file under a 'ConnectionStrings' section, specifying details like the data source and database name.
Outlines
📚 Setting Up GraphQL with Hot Chocolate and Entity Framework
This paragraph introduces the process of integrating GraphQL with Hot Chocolate and Entity Framework for data access in an application. The speaker discusses the necessity of using Hot Chocolate's data packages for parallel execution of resolvers, which is not natively supported by Entity Framework. The process includes installing necessary NuGet packages, creating a new folder for DTOs and services, and setting up a DbContext named SchoolDbContext. The paragraph also covers the creation of DTOs for Course, Student, and Instructor, reflecting the GraphQL schema and handling relationships and properties accordingly. The speaker also moves the Subject enum to a models layer to avoid direct schema references in DTOs.
🔧 Configuring Entity Framework with SQLite and Applying Migrations
The second paragraph delves into the configuration of Entity Framework with SQLite as the database. The speaker explains the process of setting up a SQLite package, configuring the connection string from appsettings.json, and ensuring the SchoolDbContext inherits from DbContext. The paragraph details the creation of database migrations using the .NET CLI, addressing issues with the Subject enum's namespace, and making necessary adjustments to the GraphQL schema. The speaker corrects the many-to-many relationship between courses and students by adding a navigation property in the Student DTO and adjusts the Instructor DTO to reflect the relationship with courses. The paragraph concludes with the application of migrations during startup using a DbContext factory and the migration process in the Program.cs file.
🚀 Wrapping Up Database Setup and Previewing GraphQL Implementation
In the final paragraph, the speaker wraps up the database setup process, successfully generating the school.db file. The speaker reflects on the lengthy process and decides to split the tutorial into two parts, with the first part focusing on Entity Framework setup and the second part dedicated to GraphQL and Hot Chocolate features. The speaker invites viewers to skip the database setup if they already have one and looks forward to more engaging content in the next part of the series. The paragraph ends with an invitation for feedback, a call to action for viewers to become members, and an encouragement to like or subscribe for more content.
Mindmap
Keywords
💡GraphQL
💡Hot Chocolate
💡Entity Framework
💡Data Access
💡DTOs (Data Transfer Objects)
💡DbSet
💡DbContext
💡Migrations
💡Many-to-Many Relationship
💡SQLite
💡Program.cs
Highlights
Introduction to implementing services for data access using Entity Framework with Hot Chocolate GraphQL.
Installation of Hot Chocolate's data package to integrate with Entity Framework and handle parallel resolver execution.
Explanation of the necessity of the Hot Chocolate.data.entityframework package for parallel query execution.
Creation of DTOs (Data Transfer Objects) to reflect the GraphQL schema and describe database layout.
Demonstration of how to map GraphQL types to DTOs for Courses, Students, and Instructors.
Decision to move the Subject enum to a models layer for better separation of concerns.
Adjustment of the GraphQL schema to reference the moved Subject enum from the models layer.
Setup of the DbContext for the application, named SchoolDbContext, and its relation to the DTOs.
Configuration of the database connection string using appsettings.json and dependency injection.
Use of SQLite for simplicity in setting up the database and the installation of the necessary package.
Creation of database migrations using the .NET Entity Framework Core tools.
Correction of errors related to the Subject enum import and the necessity of the .NET Framework Design package.
Adjustment of the database schema to reflect many-to-many relationships between Courses and Students.
Removal and re-creation of database migrations to incorporate the many-to-many relationship.
Application of database migrations on startup through the Program.cs file for automated database setup.
Completion of the database setup and the generation of the school.db file.
Announcement of splitting the tutorial into two parts, focusing on GraphQL and Hot Chocolate in the next part.
Invitation for feedback, questions, and suggestions in the comments section for further engagement.
Transcripts
now that we've covered all the graphql
operations in our graphql api with hot
chocolate we're going to move on to
implementing services for data access so
specifically we're going to have our
services use entity framework to access
a database and this is pretty much
essential to most applications but this
is also going to allow us to demonstrate
more advanced hot chocolate graph heal
features in the future such as data
loaders pagination sorting filtering all
that fun stuff so that being said first
off we're going to install some packages
so that we can integrate with entity
framework so let's go to our project and
manage nuget packages and we want hot
chocolate.data.entity
framework and the reason we want this
instead of just regular entity framework
by itself is because hot chocolate will
actually execute some resolvers in
parallel and by default any framework is
going to freak out if you try and
execute multiple operations at once so
this package will take care of that so
that we can execute those queries in
parallel so let's install that so as
always with nad framework we're going to
have to create our db context and also
our dtos that are going to describe how
our data is going to be laid out in our
database so let's come over to our
project let's create a new folder let's
have
dtos and let's have services as well and
in services i'm going to have my db
context so let's create that i feel like
our application needs a name but i'm
just going to call this school
db context so create that and we'll also
create our dtos while we're here so as
expected this is going to kind of
reflect our graphql schema where we're
going to have a course dto
as well as a student dto and lastly
we'll also have m instructor dto so as i
mentioned this is going to reflect our
schema so i'm going to bring that up
just for reference i believe we have
this in our queries we have our course
type so for now on this course type i'm
just going to grab all of these
properties and move those over to our
dto and just change them from here so we
are still going to have an id and a name
we are going to have a subject i'm going
to come back to this but let's get rid
of this
hot chocolate attribute we have here we
don't need that for instructor we're
going to point to our instructor dto and
for our students we're going to point to
our student dto let's also have a
foreign key property for this instructor
so that's going to be a good and we'll
call this instructor id by convention so
now all we have left is subject so we
could just import this from our graphql
schema but i feel like our dtos should
not reference our schema so we could
just redefine a different subject enum
here
but i feel like what i'm gonna do
instead is just move the subject enum
into a layer that's kind of in between
our dtos and our graphql schema which
might not be the cleanest approach like
maybe it would be a good idea to
have your subject enum also in your
dto's layer but instead i'm going to
have a models folder here and we're
going to add a new item here we'll call
this subject it's not going to be a
class just going to be that enum and
let's just
move that all in here so cut it out
paste it in here delete it from our
course type
and now i'm going to import that in our
schema i believe other places in our
schema actually referenced that subject
so i'm kind of happy about this because
we had our mutations namespace
referencing our queries namespace which
felt off so now we've kind of moved
everything to a centralized location in
our model but that should be everything
that needs to be updated in our schema
let's head on back to our course dto
import subject from our centralized
models namespace now let's move on to
instructor id so i'm going to open up my
instructor type on my graphql schema and
just grab all of these properties and in
fact i don't think any of these are
going to be different so we got our
primary key and then just all the
regular scalar properties so that should
be all good and then lastly we have our
student dto gonna head into my student
type and this should be
pretty much the same as instructor went
where we can just
paste all of that in here
get rid of our hot chocolate attributes
definitely don't want those here and
that should be good to go so now that we
have all of our dtos defined let's head
back to our db context and define db
sets for each of those dtos so our db
context knows that we want a table for
each of those objects so we're going to
have a db set import that from entity
framework
for our course dto import that from our
dto's namespace and this will be the
courses and then we're gonna have two
more db sets one for instructor dto
these will be our instructors and then
student dto these will be our students
so now that our db context is ready we
can register that in our services
so we're going to take our services and
we're going to add a pooled db context
factory so let's specify our db context
type the school
db context and now we just need to
configure it so i am just going to use
sql lite here because in my opinion
that's the easiest to set up but we are
going to need a package for that so
let's just search for sqlite and we
actually want
microsoft.netframerecord.sqlite so let's
install that and now we can use sqlite
so there we go import that from
microsoft.net framework and now our
connection string let's actually load
that from our appsettings.json
so we're going to have a variable for
that here and we're going to have to get
that from our configuration which
isn't in our startup class so we're
going to get that
through the constructor so let's define
a field for it this should be the i
configuration so import that from
microsoft.extensions and we should be
able to get that through the constructor
so let's generate that and our
connection string is gonna be from that
configuration so we can get connection
string and we'll just call ours default
so this is going to get loaded from our
appsettings.json
so let's head over to our app
settings.json and we are going to have a
connection strings key right here
and we're going to have default and
typical sql like connection string we're
going to have data source equals and
then the name of our database we'll call
this school.db
so this should be all good here we're
getting this error because
our school db context does not inherit
from db context as it should there we go
error goes away and our db context
definitely would not work if we didn't
inherit from db context so that's a good
fix right there so now next up as always
with nad framework we are gonna have to
create migrations for our database so
let's open our api in a terminal and the
command to create a migration i hope i
remember this so it's dotnet ef
migrations oh i was so close but i just
looked at the documentation because i
could just never remember this so we're
gonna add a migration and we'll call
this initial and we're actually gonna
build air real quick and this is related
to moving subject to the model's
namespace so gotta import it here in our
course type input as well there we go
let's try migrations again and we messed
it up again so our query type also needs
to import subject that was a pretty big
breaking change let's try again let me
build first make sure it actually builds
there we go successful so we should be
able to actually add the freaking
migration now oh and i forgot we need
microsoft.netfromrecord.design as a
package so let's install that real quick
this is not going as expected but that's
okay so let's search for that package
and install that real quick and try
again this is only the fourth time not
too bad and hopefully last but not least
we also have to add a constructor in our
db context that accepts db context
options so let's do that real quick so
we can actually just generate that and
we want these options to be for our
school
db context so we got the constructor
let's try i think this is like the sixth
time but we should get it here there we
go we got our migrations so looking good
got all of our tables in here and
actually i think our relationships are
kind of messed up so our students table
is gonna have a course dto id
but in reality our student
should be capable of being in many
courses so i think what we have to do on
our student dto
is to find another property here and
this is going to be an i innumerable
of course dtos and we'll call those
courses and this will tell enemy
framework that we want this many-to-many
relationship between courses and
students and i think i actually also
want a navigation property on instructor
dto just to describe that one instructor
can have many courses so let's remove
that old migration so dot net ef
migrations remove so there we go
successfully removed and let's add
initial again and now this definitely
worked this time because we have this
join table for course dto to student dto
which reflects the many to many
relationship between courses and
students so now we could apply our
migrations from the terminal down here
but i think what i want to do instead
is automatically apply migrations on
startup so let's actually go into our
program.cs and this is where we can
actually apply our migrations against
our database so we're going to need our
host and we get that back from this
build method right here so we build our
host using the host builder and
eventually we are going to run our host
but in between all this what we're going
to do is take our host services and
we're going to get a required service
here so import that from microsoft
extensions and we want our school db
context and actually before i get too
far in this i already know that our
school db context is registered as
scoped so first we are going to have to
create a scope so we get back this i
service scope which eventually is going
to have to be disposed so let's wrap
that into using and now we can take our
scope
and take our service provider and
resolve not
a straight up school db context and the
reason we don't do that is because we
registered a db context factory not the
actual db context so we are going to get
an idb context factory for our school db
context so put that into a variable and
now this is going to be in a using
statement but we're going to get back
our school db context and we'll take our
context factory and create our db
context and now all we have to do is
take our context take our database and
migrate and that'll apply our migrations
on startup so let's go ahead and run
this and see if our database gets
generated so no errors we successfully
started and if we look over here in our
project we have our school.db
so we finally got our database set up
and i think i'm going to stop myself
right here and actually split this
episode into two parts so this part one
was all about just setting up entity
framework and getting our database set
up which actually took longer than
expected so this part was kind of like a
prerequisite for the next part which is
going to be fully focused on graphql and
hot chocolate i suppose i could have
just done all of this db setup offline
but i want to be fully transparent in
this series if you already have a
database then hopefully you skip this
video and are moving along to the next
part so hopefully this was helpful for
getting set up with any framework of
course next time we're going to do much
more fun things but if you have any
questions criticisms or concerns be sure
to leave them below in the comments
section if you enjoyed the video or are
enjoying the channel consider becoming a
member other than that leave a like or
subscribe for more thank you
浏览更多相关视频
Full Node.js Deployment - NGINX, SSL With Lets Encrypt
AR Indoor Navigation from scratch in under 30 minutes with Unity 6
Connect a PostgreSQL database to a Spring Boot Application Tutorial
Generate C# Model from existing Microsoft SQL Server Database
Nestjs backend rest api - Ecommerce project. Introduction & setup.
DVWA Setup in kali linux | dvwa blank page solution
5.0 / 5 (0 votes)