Create a database using Entity Framework Core in Blazor

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we will learn how to create a database using Entity framework core in a Blazer web app in net 8 let's start Visual Studio 2022 click create a new project from the all project types drop down select other and select the blank solution template and click next let's give the solution a name say simple book catalog and click create let's start a project for our domain layer right click the solution in solution Explorer and select add new project in this drop down here select library and select the class Library template here and click next let's give the project a name since this project represents our domain layer let's name it simple book catalog. doain so copy the solution name and paste it here and add the dot domain suffix and click next make sure net 8 is in the dropdown and click create we don't need the class one class here so let's right click the class one. CS class file and click delete let's create a folder inside this project for our book class so right click the project in solution Explorer and select add new folder let's name the folder entities right click the entities folder and select add class name the class book and click the add button let's remove these using statements here press control period and click remove unnecessary usings make the class public so that it can be accessed outside the project a book needs to be uniquely identified so let's create a public int property called ID a book will also have a title so let's create an unable string property called title similarly create a property for the author's name call it author then create a public nlel datetime property called publication date now a book belongs to a category so let's define an enum for that right click the project in solution Explorer and select add new folder name the folder enims now right click the enim folder and select add class name the class category and click add again remove the using statements and mark the class public change the class to an enum let's define a few members such as science technology Fitness travel let's go back to the book class and Define a public property of type category let's bring the Nam space simple book catalog. doom. enms and call the property category click the save all button our domain layer is now complete let's create a project for our application layer right click the solution and select add new project from recent project templates double click the class Library template let's name the project simple Book catalog. application and click next we have net 8 in the drop-down so let's click create in this application project we want to Define an interface for our repository this repository interface needs to be able to access the book entity class in the domain layer so let's let's add a project reference from the application project to The Domain project so right click the dependencies node and select add project reference and select simple book catalog. domain here and click okay let's delete the class one. CS class file right click the application layer project and select add new folder name the folder interfaces right click the interfaces folder and select add new item select interface from the list and name the interface iBook repository and click add let's remove these using statements and make the interface public let's click save all now that we have our repository interface in place we need to implement the repository this repository implementation will belong to the infrastructure layer so let's go ahead and create a project for that right click the solution and select add new project double click the class Library template let's name the project simple book catalog. infrastructure and click next again we have net 8 here click create the infrastructure project needs to use the repository interface that's defined in the application project so let's add a project reference to the application project delete the class 1. CS class file right click the infrastructure project and select add new folder name the folder repositories now right click the repositories folder and select add class name the class Book Repository and click add let's remove the using statements and mark the class public now this class needs to implement the iBook repository interface so let's Implement that bring in the namespace simple book catalog. application. interfaces now this repository class has to work with the data access API since we are going to use Entity framework core object relational mapper as a data access API we need to go ahead and install the new get package for that in particular we need to install the new get package for the database provider that we want to use so in our case we're going to use SQL Ser Express local DB let's install the appropriate Nate package so go to tools new get package manager and package manager console set the default project to infrastructure and type in install Das package microsoft. Entity framework core. SQL server and press enter in Entity framework core we need to create what is known as a context class so right click the project in solution Explorer and select add new folder and name the folder fer context now right click the context folder and select add class name the class simple book catalog DB context and click add remove the using statements Mark the class public this class has to inherit from Entity framework course DB context API so let's do that bring in the namespace microsoft. Entity framework core now in order to talk to the database the DB context class needs to know what database provider to use and the connection string information so here we can declare a Constructor into which we can inject DB context options of simple book catalog DB context and call it options and pass this information to the base class Constructor now the job of the context class is to wrap the domain entities into a data model by exposing them as DB sets so let's create a public property of type DB set of book bring in the namespace simple book catalog. domain. entities and call the property books this books property will be mapped to a corresponding table named books once we create the database let's go to the book class the different properties of the book class will be mapped to the corresponding columns in the books table now by convention the ID property will become the primary key and since we have defined the title and author properties as being null LEL the corresponding title and author columns will be allowed to have null values if we want to overrate these default conventions we can use data annotations and fluent API let's first see how to use data anotations data anotations are attributes that we can apply on model properties so let's say for example the title column should have a mandatory value so it should not allow nulls so we can apply the attribute required bring in the namespace system. component model. dat annotations likewise we can specify the maximum number of characters the column can hold by using the max length attribute and passing in a number let's copy the two attributes for the author property as well note that we can use string length instead of max length because it adds support for client side validation as well another way to configure the model is to use the fluent API note that we are not going to use fluent API for our demo we're going to stick to data annotations but for the sake of completion let me demonstrate how to use the fluent API so let's go to the simple book catalog DB context class and here we can override the on model creating method so say protected override and choose on model creating and remove the call to the base method and inside this method we can say model builder. entity of book do property e goes to e. title do is required do has max length 100 we can copy this and paste it below and change title to author for enforcing this on author as well again as I already said we're not going to use fluent API so let's remove this method now that our context class is ready we can use this context inside our repository so go to the Book Repository class and Define a Constructor normally we can inject the context class directly into the Constructor but since our presentation layer will be a Blazer web app which support for interactive server rendering meaning we add support for Blazer server we need to inject idb context Factory of simple book catalog DB context let's call it Factory create a private readon field of type simple book catalog DB context and call it context and inside the Constructor initialize context to factory. cre DB context since we are injecting idb context Factory into the Constructor we need to register the service in the startup project so let's create a new project for our presentation layer right click the solution in solution Explorer and select add new project from this drop down here select Blazer and select the Blazer web app app template and click next let's give the project a name of simple book catalog and click next so here in the drop- down we have net 8 selected we have the authentication type set To None let's leave the interactive render mode set to server so this configures interactive server rendering using the Blazer server hosting model and let's leave the interactivity location set to per page or component so this means that the Entre application will use static Ser rendering but then interactivity can be enabled on a per component basis using interactive server and let's leave this checkbox check and click create let's set this project as a startup project so right click the project and select set as startup project now we want this project to reference the application and the infrastructure projects so right click the dependencies note and select add project reference and select the application and infrastructure projects and click okay okay now open the program.cs class file and here let's register the services required for DB context Factory so say Builder doservices do add DB context Factory and pass in simple book catalog DB context as a type argument bring in the namespace simple book catalog. infrastructure. context and pass in a Lambda expression as a method argument so say options goes to create a code block and inside that say options. SQL Server bring in the namespace microsoft. Entity framework core we can pass in a connection string now instead of hardcoding a connection string we can fetch it from a configuration file so let's say Builder do configuration dog connection string and pass in a string with the name of simple book catalog connection copy the string and open solution Explorer and double click app settings. Json file put a comma and Define a connection strings section and inside that paste the connection string name and give it a value of server equals local DB back SLB SL mssql local DB semicolon database equals simple book catalog semicolon trusted _ connection equals true this is the connection string to use if we want to connect to SQL or Express local DB now it's time to create the database in order to do that we can use Entity framework code migrations so we need to do two things we first need to create a migration and then apply that migration so go to tools new get package manager package manager console and make sure the default project is set to the infrastructure project now to use migrations we need to install a set of tools so for example if we just go and say add- migration initial and hit enter we see we get an error so let's install the required tools so say install Dash package microsoft. entityframework core. tools now even after installing the tools if we say add- migration initial you see we get an error this is because our startup project does not reference microsoft. entityframework code. design so let's change the default project to simple book catalog which is our startup project and now install the package microsoft. entityframework code. design now change the default project back to infrastructure and try creating migrations it will succeed so let's say add- migration initial if you open solution Explorer in the infrastructure project we can see a migrations folder and if we expand that folder we can see a class file that ends with initial docs that file is visible right here we see it contains a method called up this method contains instructions on what changes need to be made to the database when we apply that migration so in this case it will go ahead and create the books table similarly it contains a down meth thir that contains instructions on what changes need to be made to the database when we revert or undo a migration so in this case it will drop the books table so the Entity framework core migrations feature lets us evolve the database schema as the model changes now go back to package manager console and apply the migration type update Das database and hit enter let's check if the database got created go to view SQL or object Explorer expand SQL Server expand the local DB instance and then databases we see we have our simple book catalog database expand that and expand the tables note we have our books table now if you further expand that and the columns we can see the various columns these columns correspond to the properties of the book entity class and as you may notice the title and author columns have their maximum length up to 100 characters and have the notnull definitions as well so this is due to the data annotations that were applied to the properties on the book entity class that's it for this video hope you found the video useful thanks for watching
Info
Channel: CodeGanesh
Views: 2,848
Rating: undefined out of 5
Keywords: create database, entity framework core, ef core, .net 8, blazor, database, blazor .net 8, .net, create database ef core, blazor web app, .net 8 blazor, create database entity framework core, ef core how to create database, ef core create database, how to use ef core, use ef core in blazor, ef core blazor, ef core blazor .net 8, entity framework core blazor, entity framework core blazor .net 8, .net ef core, create database with ef core, ef core migrations, codeganesh
Id: LGjDjz0qUEI
Channel Id: undefined
Length: 16min 43sec (1003 seconds)
Published: Sun Dec 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.