Blazor CRUD Tutorial: Step-by-Step Guide with Entity Framework Core and .NET 8

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to the course Blazer CR jumpstart with Entity framework core in net 8 I'm Ganesh and I'll be your instructor for this course so in this course we'll learn how to perform crud operations using Entity framework core in a Blazer web app inet 8 through this course we'll be building a simple book catalog app that uses static server rendering for the most part and we'll build a create page that lets us add a new book to the app a list page that displays all the books an edit page that let us update the details of a single book and finally for the delete operation we'll Implement a simple razor component that shows a confirmation dialog before deleting a book now since the application uses static server rendering the delete button won't be interactive so it'll be adding interactivity to the application on a per component basis along the way we'll be learning other features of Blazer in net 8 such as enhanced navigation and form handling and streaming rendering this course is ideal for developers who have some experience with blazer and Entity framework core and who want to learn how to perform crud operations using these two Frameworks in net 8 so thank you and I hope to see you on the other side this course uses net version 8.0 which you can download from this URL here and for development I'll be using visual studio 2022 IDE which you can download from this URL here and during installation make sure you have asp.net and web development workload checked and under individual components make make sure you have SQL Ser Express local DB checked as well in this video we will learn how to create a database using Entity framework code 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. domain so copy the solution name and paste it here and add the domain surfix and click next make sure net 8 is in the drop down and click create we don't need the class one class here so let's right click the class 1. 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 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 so similarly create a property for the author's name call it author then create a public null level datetime property called publication date now a book belongs to a category so let's define an enom for that right click the project in solution Explorer and select add new folder name the folder enums now right click the enims 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 namespace simple book catalog. domain. 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 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 here 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 unmark 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 n get package so go to tools n get package manager and package manager console set the default project to infrastructure and type in install Das package microsoft. entityframework core. SQL server and press enter in Entity framework core we need to create what is known as a context class so right click C the project in solution Explorer and select add new folder and name the folder 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 de 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 annotations data anotations are attributes that we can apply on model properties so let's say for example 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 other 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. property e goes to e. tile 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 with support for interactive server rendering meaning We'll 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. creb 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 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 entire application will use static server rendering but then interactivity can be enabled on a per component basis using interactive server and let's leave this checkbox checked 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 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. usql 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 ction 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 slash mssql local DB semicolon database equals simple book catalog semicolon trustcore connection equals true this is a 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 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 Das package microsoft. Entity framework 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. Entity framework code. design so let's change the default project to simple book catalog which is our startup project and now install the package microsoft. enti framework code. design now change the default project back to infrastructure and try creating my 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 so in this case it will go ahead and create the books table similarly it contains a down method 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 a model changes now go back to package manager console and apply the migration type update Dash database and hit enter let's check if the database got created go to view SQL Ser object Explorer expand SQL Server expand the local DB instance and then databases we see we have a 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 not null definitions as well so this is due to the data annotations that were applied to the properties on the book entity class and if we right click the books table and select view data we don't have any data to start with so in the next video we'll learn how to save data using Entity framework core in a Blazer web app inet 8 in this video we are going to learn how to save data to a database using using Entity framework core in a Blazer web app in net 8 and we'll use the edit form component in Blazer to accept input data let's add a method to the iBook repository interface for performing the create operation so let's say task add async book bring in the namespace simple book catalog. domain. entities and call the parameter book Let's implement this method in the infrastructure project so go to the infrastructure project and open the Book Repository class and implement the interface now say context. books. add book and await notice we have the async modifier added here context do saave changes async now let's work on the presentation layer so go to the simple book catalog project and expand the components folder first let's make some changes to the main layout component so expand the layout folder and double click main layout. Razer now remove the sidebar div with its navigation menu and also remove the top row div and let's set only the paring top for this article here so set it to pt5 and since we're not using the N menu component let's go ahead and delete that component and expand the pages folder and delete all all the components inside that folder now let's add a new razor component which will contain a form to add a new book right click the pages folder and select add razor component name the component add new and click add we want this component to be a routable component so that it can be accessed via a URL so let's set the page directive at the top so say at page SL add- new now if you run the applic ation and navigate to/ add- new we can see the add new heading that was present on our component we don't need the heading so let's remove it now let's set the text that's displayed on the title bar of the browser window or the browser tab by using the page title component so say add new book in the code block let's define a public property of type book this book entity is present in the domain layer so let's bring in the name namespace simple book catalog. domain. entities normally we wouldn't want to reference the domain entities directly in the presentation project rather we want to use a view model but for this demo I'll stick with the domain entity let's put the using directive in the imports. Razer file so that we don't have to import it in every razor component going back to the add new component let's call the property book and instantiate it as well now let's create our form here create a div with the bootstrap class row and justify content Center and inside that create ative with the class call six let's use the edit form component to create our form set method equals post because this form will post to the server every form needs to have a name so set the form name parameter to add book form and set the model parameter to the book property we just created and lastly turn off autoc completion for the form by setting autocomplete equals off now inside the edit form component create a heading with the text add new book then create a div with some margin bottom so say div class equals mb3 Define a label element with for set to title and class form label the text of that label should be title and then let's use the input text component with ID set to title and use a bind Das value razor directive attribute setting it to book. title and set the class attribute to form control and Shadow none copy the entire Dev and paste it below three times now for the second label element let's set the for attribute to author and set the label text to author and also set the ID attribute of the input text to author and bind value razor dative attribute to book. author for the next label set the for attribute to publication date and set the text to date published now instead of input text let's use input date so change input text to input date and set it ID attribute to publication date and set bind value to book. publication date now inside this div let's remove the input text component because we want to use input select set the for attribute of the label to category and set the label text to category and Below let's use the input select component and set its ID attribute to category set bind value to book. category and finally set the class attribute to form control Shadow none now let's set a default option for this input select component so inside the input select component Define an option element with value set to zero and set the content to select category next we want to Loop through each member of the category enum so let's use the for Loop say at for each V category in enim dog values and pass in type of category now this category is present in simple book catalog. domain. enm namespace so let's bring that namespace in now we can put that using directive in inputs. raer file now go back to the add new component and inside the for Loop Define an option element with its value set to at category and set it cont content to at category do2 string finally we'll create a div with a class mb3 and inside that let's define a button element with its text set to submit and class set to BN BN primary Shadow none following this div let's use the data anotations validator component which enables form validation and lastly use the validations summary component to display a list of all errors now when the button is clicked the form will post to the server so let's use the on valid submit parameter of the edit form component and set it to add book down in the code block create a private async method that returns a task and call it adbook now inside the adbook method we want to be able to access the form data so let's set the supply parameter from form attribute on the book property now once we do this the book property will be supplied from form data and then we can use the book property inside the adbook method now we want to save the book and we already have a repository for that so inject iBook repository bring in the namespace simple book catalog. application. interfaces and call it repository put the using directive in inputs. Riser file and go back to to the add new component also once we perform the create operation we want to redirect the user to a new page for that we need to use navigation manager so let's inject navigation manager call it navigation then scroll down and inside the adbook method say await repository. add async and pass in book then navigation. navigate to let's pass in a slash to go to the root of the app and since we are injecting iBook repository we need to register the Book Repository service so open solution Explorer go to program.cs and here say builder. services. add scoped and for the type arguments pass in iBook repository bring in the name space comma Book Repository and bring in the name space for that as well now let's run the app first let's demonstrate an important feature of Blazer in net 8 called Static server rendering right click the page and click inspect and go to the network Tab and navigate to/ add- new we can see that the component and all other assets got rendered from the server so this is called Static server rendering so we have our form with all the elements but there's an issue with the select list here we have signs as a default option rather we want select category as a default option we'll fix that in a bit let's submit the form without entering any data click the submit button we see a list of all the validation errors with their default error messages now go back to visual studio and go to the add new component for this input select component we have the select category options value set to zero but if we go to The Domain project and expand the enum folder and open the category enum we see by default the enum members have their values starting from zero that's why we see signs as a default option selected so let's set signs to one and expand the entities folder and go to the book class decorate the category property with the enum data type attribute pass in type of category and set the error message to please select a category so when the user does not select a category this error message will be displayed likewise let's set an error message for the title property when a value is not supplied in the required attribute passing error message equals please provide a title and for the author property let's set the error message to please provide the author's name now let's run the app and navigate to/ add- new we can see our form and we have select category as a default option and if you click the submit button we see our custom error messages now let's demonstrate another feature of Blazer inet 8 called enhanced form handling right click the page and click inspect and click the network Tab and clear the network trace and reload the page once again we see all the assets getting downloaded from the server now watch the loading spinner here once I click the submit button we can see a small blip and on the right hand side here all the assets got downloaded from the server once again so this means that we're not taking advantage of enhanced form handling by default enhanced form handling is disabled so let's go back to visual studio and enable enhanced form handling by setting the enhanced parameter of the edit form component to true now run the app right click the page click inspect and click the network Tab and navigate to the add new component and once again look at the loading spinner when I click the submit button we see there is no blip occurring this time so here on the right hand side we can see that instead of returning all the assets from the server a fetch request was made by blazer. web.js for the add new component and only that component was rendered and the UI was updated finally Let's test our form enter some data and click the submit button if we wait for a while it will navigate to the root URL and since we don't have a page for that endpoint we get an error 44 response let's go back to visual studio and go to view SQL Ser object Explorer and open the simple book catalog database and right click the books table and say view data we see that a record got inserted into the database in the next video we'll learn how to read data from a database using Entity Framework core in a Blazer web app in net 8 in this video we're going to see how to read data from a database using Entity framework core in a Blazer web app in net 8 let's add a method to the application project for performing the read operation so in the application project expand the interfaces folder and double click iBook repository let's add a member task of listof book get all a sync now let's implement this method in the infrastructure project so inside the infrastructure project expand the repositories folder and double click the Book Repository class let's implement this interface and inside the method say war books equals await context. books. toist async and return books now let's move on to the presentation layer in the simple catalog Blazer web app project expand the components folder and expand the pages folder and double click add new. Razer now we want to add a link to a page where we show a list of all books so right below the submit button let's add an anchor element with the text back to list set the href attribute to slash and class attribute to BTN BTN secondary Shadow none and we would like to add some margin so say ms3 so now let's create the list component so right click the pages folder and say add razor component and call the component list now we want this component to be a routable component so add a page directive to the top say at page and specify a route template of slash now before we proceed any further I want to demonstrate a feature of Blazer in net 8 called enhanced navigation so let's run the app and as you can see here at the root URL we have the list component rendered now right click the page and click inspect and click the network Tab and navigate to the add new component so here at the bottom we have the back to list button now watch the loading spinner when I click the back to list button you see that there is no blip and on the right hand side here we have a fetch request initiated by blazer. web.js for the list component so instead of downloading all the assets from the server we made a request only for the component we needed and that component was rendered and the page was not reloaded so this improves the user experience for the application so this means that enhanced navigation is by default enabled but if we want to turn off enhanced navigation we can do that too so go back to visual studio and go to the add new component and to the Anchor element let's add an attribute data enhan now equals false now run the app once again right click the page click inspect and click the network Tab and navigate to the add new component once again watch the loading spinner when I click the back to list button we see this time there's a blip and on the right hand side here we see all the assets got downloaded from the server instead of making a request only for the component we needed so this means that a page reload was going on since we turned off enhanced navigation for the link let's turn it back on from the anchor element remove the data andan now attribute now let's work on the list component so open list. Razer and here remove the heading and use the page title component to set the title for the page which will be displayed in the browser tab let's set the text to book list and in the code block create a private nullable field of type list of book and call it books and we want to get the list of books from the repository so at the top here say at inject iBook repository and call it repository we want to get the list of all books once the component has been initialized so we have a life cycle method for that so in the code block here say protected override and choose oninitialized Asing and inside this method say books equals await repository. get all async notice we got the async modifier added to the method now let's add some razor markup for displaying these books so at the top here create a div with a class row justify content Center and inside that create a div with a class call 6 now first let's check if books is null so at if books is null create a div with a class book item and inside that say loading books please wait otherwise we want to check if the books variable contains any books so say else if books. any let's use a for each Loop to Loop through the books and create a div with a class book item item and inside that let's create a div with a class book card and another div with the class book card body and create a H5 Hing and set the content to a razor expression so say at book. title and after the heading say byy at book. author and let's use a vertical bar at book. publication date since the publication date is nullable let's use a question mark do two string and we want to display the date in the format month day comma year so let's specify the format string and finally if there are no books to be found say the classical book item and set the content to no books found now if you run the app we can see the single book that we added in the last video of course the UI does not look good we'll fix that in just a bit but for now I'm going to bring Visual Studio on the browser side by side and I want to create a link in the list component to navigate to the add new component so up here create an anchor tag with the text add new and set the HF attribute to add- new and set the class attribute to BTN BTN primary Shadow none and let's add some margin at the bottom so say mb3 now if you want to see the page getting updated instantly click on the drop- down arrow next to the hot reload button and make sure hot reload on file save is checked otherwise click on it to check it and click the save button and we see the add new button on the right hand side now let's add some books to the catalog by clicking on the add new button now it's time to style the UI so open solution Explorer and right click the pages folder and select add new item in the search bar search for CSS and click stylesheet and name the file list. razor. CSS now in the list component we have a div with the class book item and we would like to style that that so inside the CSS file say do book- item open and close curly braces set paring to 1.5 RM and click the save button to see the changes similarly set margin bottom to one remm set box Shadow to 0 0 0.5 REM and specify the color r GBA 0 0 0 0.3 and finally let's add some border radius set border radius to 0.5 RM now that we have fixed our UI let's talk about a couple of things go to list. Riser and scroll down we have this div with a class book card that displays the details of a single book this is a good candidate for a reusable component so copy this markup here and open solution Explorer and right click the components folder and select add razor component and name the component book card. Razer now replace the heading with the copied markup so paste it here and inside the code block create a public property of type book we need to make it required let's turn this property into a parameter so that its value can be supplied from the parent component component so decorate the property with the parameter attribute now in this markup here we see squiggly lines so replace book with the book property now go back to the list component and instead of this markup here say book card and set the book parameter to book and now let's run the application we see that the app works just fine finally let's talk about another another feature of Blazer in net 8 called streaming rendering let's go back to visual studio and in the list component scroll down and here we are getting book information from Cur Express local DB database this does not take much time but let's say the data is present on a separate database server and there is some delay involved in getting the data let's simulate that kind of delay for our application by using await task. delay 3000 so basically we are waiting for 3,000 milliseconds or 3 seconds before getting the data so while it is taking some time to get the data that is simulated by this task. delay call the books variable will be null and if we scroll up we can see we are checking if books is null in which case we're displaying loading books please wait message let's run the app we can see we getting the loading spinner here in the browser and once the 3 seconds have elapsed we're getting all the book data however we're not seeing the loading books message this is happening because only after the book data is retrieved from the database the page will be rendered and sent to the client browser till then the page will still be loading and we won't see anything so this definitely harms the user experience for our application let's turn on streaming rendering go back to the list component and say at attribute stream rendering now let's run the app as you can see we have the initial UI displayed in the meantime data is being fished from the database and once data is available that data will be streamed into the response and displayed in the UI we don't need streaming rendering for our simple application so let's remove this attribute and remove the task. delay call as well in the next video we'll learn how to update data using inty framework core in a Blazer web app in net 8 in this video we'll learn how to update data in a database using Entity framework core in a Blazer web app in net 8 and we'll use the edit form component in Blazer to accept input data let's add a method to the iBook repository interface to get a book by ID so that we can then update that book so in the application project expand the interfaces folder and double click iBook repository and say task of book make it null LEL get by ID async int ID Also let's add a method to update that book so say task update aing book book Let's Implement these two methods in the infrastructure project so in the infrastructure project expand repositories and double click the Book Repository class let's implement the interface and inside get by ID async method say War Book equals await Contex text. books. first. default async e goes to e. ID equals equals ID then let's return that book and inside update Asing method say context. entry book do state equals entity state. modified and then await context. saave changes async let's work on on the presentation layer in the simple book catalog project open the book card component and after the dev with the class book card body Define a div with the class actions and inside that define an anchor element with the text edit and for the HF attribute value we need to get the ID of the current book so let's use a razor expression so say at open and close parenthesis since we want to pass in a string along with the dynamic value let's use string interpolation say dollar within double quotes slash edit slash within curly braces book. ID and finally set the class attribute to BTN BTN warning Shadow none now let's style this bookart Dev so that there is some space between the bookart body Dev and the actions Dev so right click the components folder and select add new item and search for CS and click stylesheet and name the file book cart. razor. CSS so let's use the class selector say book- card within curly braces display Flex Flex Direction row justify content space between let's run the app we can see the list of books along with their correspond responding edit buttons let's try clicking one of them we can see it takes us to a URL sledit sl3 the value three is the IDE of the third book we Are editing since we don't have a page for this endpoint we get a 44 not found error so now let's implement the edit page so go back to visual studio and right click the pages folder and select add razor component and name the component edit and click add at the top here SP specify the page directive say at page within double codes slash edit slash now this URL segment will be the ID of the book we Are editing so for this we need to use what is known as a route parameter so use curly braces and within that specify a route parameter called ID and let's constrain the route parameter to be an integer so say colon int remove the heading use the page title component and and set the content to edit book let's go to the code block now the value of the route parameter in the URL can be retrieved by defining a public property with a similar name and decorating it with a parameter attribute so let's define a public property of type int called ID casing does not matter so we can make I uppercase and decorate it with the parameter attribute now once we have the idea of a particular book we wouldd like to get information about that book so let's define a public property of type book make it nullable and call it book and when we update this book the data for this book will come from the form that we'll create in just a bit so let's decorate this property with Supply parameter from form attribute Also let's inject iBook repository so at the top here say at inject iBook repository repository once the edit page is initialized we want want to use a repository to get the information about that book so that it can be displayed on a form so override the uninitialized racing life cycle method and inside that say book and use an nising assignment operator question mark question mark equals await repository. get by id async id and now let's add the required razor markup for the form say at if book is not null we can reuse a markup from the add new component so go to the add new component copy this entire Dev and go to the edit component and paste it here let's make some changes set the form name of this edit form component to edit book form and for the on valid submit parameter set the value to edit book we'll create this method in just a bit replace the heading text with edit book and use a razor expression to evaluate the ID of the book since this is an edit scenario let's use a hidden input field to store book ID so say input type equals hidden name equals book. ID value equals at book. ID now let's define the edit book method so go to the code block and say private async task edit book and inside that say if book is not null await repository do update async book now once we update the book we need to redirect the user to the list page so at the top here say at inject navigation manager navigation and go back to the edit method and say navigation. navigate to slash now let's run the app first let's add a dummy book so that we can test editing it book title 1 2 3 book author 1 2 3 enter some publication date and set the category to signs and click submit so here we see we got the book with the title book title 1 23 added let's try editing it click on the edit button update the title to book title 456 and the author as well to book author 4556 and set the category to travel and click submit and here we see we got the title and author updated and if we click on the edit button we see we have the category set to travel as well in the next video we'll learn how to create a reusable form component for adding and updating data in a Blazer web app in net 8 in this video we'll learn how to create a reusable form component for adding an updating data in a Blazer web application in net 8 in the simple book catalog project let's open add new. Razer here we have used the edit form component to accept input data and also if you open the edit component here again we have used the edit form component with a few changes applied to it since there is some duplicated razor marker let's create a reusable form component that encapsulates edit form right click the component folder and select add razor component and name the component book form let's get rid of the heading now let's go to the code block first we need to identify whether we are adding a new book or updating an existing book so let's define a public property of type bu called is edit mode and initialize it to false so this means that by default we are adding a new book decorate the property with a parameter attribute then let's define a property property of type int called book ID and decorated with a parameter attribute and unable property of type book call it book and since we want this property to be supplied from form data let's decorate this property with Supply parameter from form attribute and let's define an expression B for a member called title that will be used to set the form's title so when we are in edit mode we need to set the form title to edit book along with the book ID so let's use string interpolation here say dollar within double quotes edit book within curly braces book ID if you are not in edit mode let's set the title to add new book now when the component is initialized we'd like to talk to the Book Repository to populate the book property so let's inject iBook repository call it reposit itory and let's override oninitialized async life cycle method and inside that we can check if is edit mode book null coing assignment operator question mark question mark equals await repository. get by ID async pass in book ID else book null coaling assignment operator new so this means that if we not in edit mode we're simply instantiating a new book now let's add the required razor markup for our form so at the top here say at if book is not null now we would like to use the edit form component so go to the edit page and copy this edit form component and come back to the book form component and paste it here let's set the form name to add or edit book form and let's set the on valid submit parameter value to add or edit book and for the heading let's use razor expression to evaluate the title member that we created earlier and we want to have the hidden input field only if we are in edit mode so let's say at if is edit mode and put the hidden input field inside this block let's now Define the add or edit book method so let's scroll down and say private async task add or edit book now this method will be called when the form is submitted now from the book form component we would like to inform the parent component that the form has been submitted so over here at the top let's define a public property of type even call back of book and call it on valid book submit and de create the property with the parameter attribute and inside the add or edit book method let's invoke that event call back by saying await on valid book submit. invoc casing and pass in the book now we are done with the book form component let's go to the add new page and remove the edit form component and replace it with the book form component set e edit mode equals false and set on valid book submit equals add book and and in the code block we don't need this book property anymore and let's have the adbook method accept a parameter of type book and pass that book argument to the adding method now let's work on the edit page let's replace this edit form component with book form component set is edit mode to true and set book ID to at ID and finally set the on valid book submit parameter to edit book and we don't need this if block so let's remove it let's go to the code block and remove the book parameter and the oninitialized racing life cycle method and for the edit book method let's add a parameter of type book and within the method let's remove the if condition and finally pass the book argument to the update acing method with all these changes in place let's run the app to see if the application works just fine add a new book with title new book title 123 an author new book author 123 enter some publication date and set the category to Fitness now let's try editing that book click on the edit button change the book title to new book title 4556 and the book author to new book author 4556 change the publication date and also change the category to travel we can see the changed book title and author name and if we click on the edit button we can see the changes in our publication date and category as well in the next video we'll learn how to delete data from a database using Entity framework core in a Blazer web app in net 8 in this video we'll learn how to delete data from a database using Entity framework core in a Blazer web app in net 8 let's add a method to the iBook repository interface for performing the delete operation so let's say task delete by ID async int ID now let's Implement that method in the infrastructure project so open Simple book catalog. infrastructure and expand repositories and double click the Book Repository class let's implement the interface first we would like to get the book by ID so say VAR book equals await get by ID async and pass in ID now check if book is not null in which case we say context. books. remove book await context. saave changes async now let's work on the presentation layer open Simple book catalog project and expand components folder and double click book card. Riser we would like to add a button to delete a book so after the edit link Define a button element with the text delete now when the button is clicked we want to show a dialogue to confirm deleting a book so let's set the on click razor dtive attribute to open confirm dialogue and set the class to BTN BTN danger Shadow none and ms3 now let's define the open confirm dialogue method in the code block below so say private void open confirm dialogue now let's create a private Boolean field for showing the DI dialogue so say private buol show confirm dialogue and within the open confirm dialogue method set show confirm dialogue equals true now let's create a reusable razor component for the delete confirmation dialog so in solution Explorer right click the components folder and select add raser component and name the component delete confirm dialogue and click add let's define a bull parameter for this component to show the dialogue next in razor markup let's use razor sytax to check if show is true then display a div element with class confirm dialog container inside that let's create another Dev with the class confirm dialogue and create a H3 heading with the text are you sure and after the heading create a div with a class deflex Flex row justify content end and mt3 and inside this div let's create a button with the text cancel set on click razor dtive attribute to on cancel which we will create in just a bit and set the class attribute to BTN BN secondary Shadow none and then create a button with the text delete and set the on click razor dative attribute to on okay and set the class attribute to BTN BN danger Shadow none and ms3 now I would like to inform the parent component when the cancel and delete buttons have been clicked so let's go to the code block and Define a public property of type even call back call it on cancel and decorate it with a parameter attribute similarly Define another property of type even call back called on okay and decorate it with the parameter attribute now let's style this component right click the components folder and select add new item search for CSS choose stylesheet and name the component delete confirm dialog. razor. CSS and click add now we want to style the confirm dialog container and confirm dialogue divs so use a class selector say dot confirm dialog container within curly braces set the position to Absolute top to zero right to zero bottom to zero left to zero set the Min height to 100 VH set display to flex Flex direction to column set align items to Center and background color to rgba 00 0.5 and finally set zindex to 2000 similarly let's style the confirm dialogue div say do confirm dialog within curly braces display Flex Flex Direction column justify content space between set minwidth to 20 RM padding to two remm border radius to one remm background color white margin top 1.5 RM and finally let's set position to fixed now let's use the delete confirm dialog component inside book card. Razer set the show parameter to show confirm dialogue and set the on on cancel parameter to cancel delete which will will create in just a bit likewise set the on okay parameter to delete book Let's create the cancel delete method go to the code block and say private void cancel delete and inside this method let's set show confirm dialogue equals false so this will effectively close the delete confirm dialogue and Below let's create another method say private async task delete book to delete the book we can use the Book Repository so let's go to the top and inject iBook repository and call it repository and also we want to navigate to the root URL so let's inject navigation manager call it navigation now go to the code block and inside the delete book method say await repository. delete by ID async pass in book. ID next set show confirm dialogue equals false and finally say navigation. navigate to pass in a slash let's run the app and try deleting a book we see the delete confirmation dialogue does not show up this is because our application is using static server rendering by default and our book cot component is rendered on the server and there is no interactivity for the bookart component either on the server or on the client so that's why when the delete button on the bookard component is clicked nothing happens now we can make the bookard component interactive by going to list. Riser and applying a rendom mode at the page level so at the top say at rendom mode interactive server so this makes the entire page interactive using interactive server rendering via the Blazer server hosting model so all the components on the page including the book card component will be made interactive now alternatively we can apply a render mode at the component level by setting the at render mode razor dtive attribute to interactive server now let's try running the app let's click the delete button we see the confirmation dialogue shows up and if you click the cancel button the dialogue closes let's click delete once again and click the delete button we see the book gets removed from the app now one last thing we can make the delete confirm dialogue more generic by declaring a nullable property of type render fragment and call it child content and decorating that property with a parameter attribute now in the razor markup here at the top instead of the heading we can render child content using Razer syntax now we can rename the delete confirm dialog. rer component to Simply confirm dialogue now let's go to the bookard component and rename delete confirm dialogue to Simply confirm dialogue and instead of a self closing tag let's use opening and closing tags and as a child content Define a H3 heading with the text you want to delete book at book. ID this way the consumer of the confirm dialog component is free to set the message text now let's run the app and try deleting a book once again we see the new message pops up let's click the delete button we see the book got removed from the app hi everyone and thanks for taking my course Blazer crud jump start with Entity framework core in net 8 in this course we learned how to perform crud operations using Entity framework core in a Blazer web app in net 8 along the way we learned some of the important features of Blazer in net 8 such as enhanced navigation and form handling and streaming rendering so I hope you found the course informative and helpful and thank you once again for your time
Info
Channel: CodeGanesh
Views: 3,284
Rating: undefined out of 5
Keywords: blazor crud, blazor crud operations, blazor crud operations .net 8, blazor crud .net 8, blazor .net 8, crud operations blazor, crud operations blazor .net 8, blazor crud jumpstart, blazor crud entity framework core, blazor entity framework core, entity framework core crud, blazor entity framework core crud, blazor entity framework core .net 8, blazor entity framework core crud .net 8, blazor ef core crud, enhanced navigation, enhanced form handling, interactiveserver, codeganesh
Id: KUrodtxHJMs
Channel Id: undefined
Length: 67min 52sec (4072 seconds)
Published: Tue Jan 16 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.