.NET 7 Beginner Course 🚀 Web API, Entity Framework 7 & SQL Server

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to the.net 7 jumpstart course now first let's have a look at what you're going to learn in the next couple of hours in a short period of time you will set up a web API make restful calls to this web API and also save data persistently with Entity framework code first migration and SQL Server database and all three types of relationships in this database the only tool you need in the beginning is Visual Studio code which is available for free we will use Visual Studio code for our implementations and make calls to the web API with the help of swagger UI an interface that lets you consume the API out of the box thanks to the.net framework later we will utilize the free SQL Server Express with SQL Server management Studio to manage our database now the backend application we're going to build is a text-based role-playing game where users can register we're going to use Json web tokens for authentication and these users then can create their own characters add some skills and weapon and then let these characters fight against each other to see who is the best of them all now in this video here is a two hour preview of the complete course on udemy you will already learn a lot in the upcoming lectures but if you want to learn more then please feel free to use the link in the video description for a huge discount and of course it also supports me to create more videos like that so thank you very much and now let's write some code the only tool we need for now is Visual Studio code additionally to that you have to download and install the.net 7 SDK of course now as you can see here the easiest way to get everything is simply Google for it for instance here I just entered Visual Studio code and you can already see the first hit you can already go to the download page of Visual Studio code and in here now you see there's a version for Windows for Linux and for Mac OS so please choose the right one for you in my case this would be the 64-bit version of the windows version for visual studio code and pretty similar the.net SDK I just entered.net SDK you can choose the first hit here as well then you see.net7 or dotnet6 now in this course you can also access all the lectures with net 6. and even.net5 and.net3.net core 3.1 but I think the versions that are really interesting are maybe still.net6 or even the latest one.net7 in this case and as you can see here you can choose all 1.7 downloads here or download.net SDK 64-bit because well the browser knows what operating system you are on but still if you want to get every SDK download option here you see there they are and in my case again this would be here the 64-bit SDK for Windows so again please download everything and install it and then we can create a new web API now as soon as the.net SDK and visual studio code is installed we can already create our first.net application which will be a web API right away now to start I created this folder here dotnet RPG for net role playing game now you can open the folder in vs code good so just right click and then here you should get the option open with code and when Visual Studio code then is open there it is we can actually have a look around now if you're already a bit familiar with Visual Studio codes I think you already know where everything are if not please feel free to have a look while you're doing that it might also be a good idea to install certain extensions so here you would find the extensions got a bunch of extensions installed here but you don't need every single one of course the first one that is interesting is this thing here C sharp for visual studio code by Microsoft itself this extension will also be suggested by vs code as soon as you create your first C sharp application it includes editing support syntax highlighting intellisense go to definition finder references just have a look pretty useful stuff now the next one is C Sharp extensions here by just creative as the description says this vs code extension provides extensions to the IDE that will hopefully speed up your development workflow and it adds some entries to the context menu like adding a new c-sharp class or interface for instance so this is already pretty pretty useful I think you can see it here a little maybe yeah you see it here in new C sharp class but we will see this of course throughout the course now the last one already actually is the material icon theme now this one is one of my personal favorites it's not really necessary but it simply provides lots and lots of cute icons for your folders and your files and maybe one more is prettier this is simply for formatting your code so maybe this is also something you want to add so that your code is a little bit more organized with one little shortcut all right so these are the extensions but now let's create our web API so we open a terminal you should see the shortcut here in your case or you just go there terminal new terminal and then let's have a look at what the.net command provides so we simply enter.net and there it is so now let's also add a dash H for help and here we see some more commands for instance also the new Command right so with that we create a new.net project or file but we also got the Run command here well to run our applications of course and also interesting the watch command down here which can be used together with run to restart the application as soon as we make changes to any file using hot reload for instance this is quite useful if you don't want to stop and start the project by yourself every single time you make any changes alright now let's see we enter maybe CLS for clear screen and then.net new and here we got some options right so there are available templates for us but to see them all we can enter.net new and then dash dash lists all right so there are a lot more as you can see here now but now finally we also get the web API here so let's use it we go down again clear the screen and now we enter dot net new web API and hit return all right so now we see some files have been generated for us in the Explorer here so let's go through them really quick at the bottom we see the weather forecast class let me close this this is just part of the default web API project we don't really need it but let's use this example in a minute and as you can see here in the meantime we get a little pop-up telling us that we should add some files and of course we want to add them you should see now that we get this vs code folder here with the launch Json and the tasks Json both are configuration files used for debugging source code format as bundlas and so on but not very interesting for us in this moment so let's have a look at another file this would be the program CS class now this is actually newsense.net 6 already before meaning until.net 6 or with net five We additionally got the startup class for configuration matters now everything is handled here in the program CS so here for instance distance we configure the app's Services as you can see here the Builder and then the services so this is a reusable component that provides app functionality we will register Services here in the future so they can be consumed in our web service via dependency injection please don't mind all these passwords right now additionally this class creates the apps request processing pipeline meaning we specify how the app responds to http requests and as you can see we are using https redirection authorization and so on with all these use extension methods we are adding middleware components to the request pipeline for instance use https redirection adds middleware for redirecting HTTP requests to https I would also like to mention that since.net 5 we get the configuration for Swagger UI out of the box this would be this line here with that we get a convenient solution to test our API we are already going to use it in the next lecture all right now let's move on with the Cs project file here we see the SDK we see the target framework.net 7 in our case and the root namespace.org PG we can also enable or disable nullable this you will see what this means later throughout this course so this means that for instance if there is a class there or a type that could be a null and we do not check for this then we get a little warning if you do not want these warnings and then you can disable that but with that then you might get trouble in other situations so we leave it at that so with that we enable nullable types in essence in our project all right we also see a package reference to swashbuckle ASP net core this is for Swagger UI and later on we will find additional packages like Entity framework core in this file so although it is now called Entity framework 7 just a side note internally we're still working with Entity framework core alright now regarding the app settings Json files we only need to know that we can add and modify some configurations here now more interesting for us is the launch settings Json file where the current environment is configured and also the application URL and with this URL we will find our running web service all right now the object and Bin folders can be ignored for now we find temporary object and final binary files here now very interesting and often used throughout this online course is this folder here controllers the first controller you see here is the generated weather forecast controller we'll get to the details of controllers later but for now it's only important to know that we can already call this get method here so let's do that next let's open the terminal and then we enter dotnet watch run to start our application and already use the Watcher and hot reload your default the browser should open there it is in my case and in the address bar here you see already the URL we've seen in the launch settings Json let's just double check 5054 is the port and now here in our launch settings Json file we see it as well so under profiles HTTP we see so beggar is the launch URL and the application URL is localhost 5054 all right and for https this would then be the port 7060 okay now what we see here already is the Swagger UI it will help us to test our web API but let's forget about Swagger for just a second you can already see the weather forecast controller here but we can also access the controller with the address bar of chrome so when we go back to vs code and here we already are in the controller we see the name of the controller which is weather forecast right so the term in front of the controller term weather forecast we also see the routing attribute which is this thing here and this thing defines how to access this controller we'll discuss how routes work in a future a lecture but for now let's just copy the name so this would be weather forecast copy this and we go back to Chrome and then we enter the route so let's just add weather forecast hit return and we get already the results now when we go back to subwega you see the controller and also the schemas here now the schemas are actually the weather forecast class and other classes that are used there in the controllers and these tell us how the result of the web API call will look so here you see the weather forecast and these are other types all right that I used here in the weather forecast date only class for instance and now above these schemas again it's actually not only the controller it's actually the get Call of the web API now we can see the available parameters in this particular case there are no parameters and we also see the expected result right so parameters here and here then the expected result and the best thing is we can try this out right here so let's do that so we just click try this out and then we click execute and here we see the request URL which is exactly the same thing we have entered in the address bar a minute ago and we also see the result a couple of random weather forecasts now we can also see the result in the network tab of the developer tools of chrome just press F12 on your keyboard and then we switch to network here we filter by fetch xhr not all fetch xhr which stands for XML HTTP requests and then let's just execute this call again and you see here is the call and in the preview here you see that the result is exactly the same all right great this works so far and now let's move on and build our own web service there's one little thing we may do before we start with the web API let's create a git repository for our project if git is not installed on your machine please do that first again you can simply Google for git and here's the result you can go to downloads and there again for every operating system there is the specific version so please download this first if you haven't already and after that on the left pane you see the tab for Source control and here we just say initialize repository or we can already directly publish this to GitHub so let's try it first with initialize repository now the thing is as you can see here here the listed changes are simply way too many we don't need to commit the bin and object folders for instance so we need a so-called git ignore file to ignore certain files and folders so let's open the terminal real quick and let's stop the app with Ctrl C and now we can simply type.net new git ignore so dot net new and then git ignore and we're already good to go let's just hit return and you see now that lots of file changes are not listed anymore because they are now ignored now we simply add our first commit message here like initial initial commits and then we can commit all changes and we're done so from now on you can choose to commit your code whenever you want to get a clean history of your changes I will do that too of course and additionally you can push your repository as you can see here again to GitHub now as well just click this button here or later this a little Cloud icon on the bottom left and make sure you're logged in to GitHub and then publish your code to private or public GitHub repository now while I am currently edit let me just publish the repository here for you so as you can see here I can now choose between private and public I will first make this private because I'm still recording but when I'm done with recording this course I will make this public and in the next lecture I will enter the the link as a text so that you can access the GitHub repository and after every single lecture then I will commit the code changes and push them so you can really watch a lecture and then get the corresponding code if you have some trouble with the code so please just have a look at the GitHub repository maybe this already helps so let me call this now.net RPG uh maybe dot Net 7 RPG because of.net RPG repository is already on my GitHub profile I make this private and now we are publishing this thing to GitHub it's uploading the files successfully published and now we can open this on GitHub and there it is so here now you can actually see or get the complete code and again with every lecture there will be a corresponding commit so far you learned how to create a web API project in.net from scratch and how to make your first web API call in the upcoming sections we will create a new controller and models for our RPG role-playing game characters additionally we will turn our synchronous calls into asynchronous calls make use of a data transfer objects or dtos and change the structure of our web API so that it meets best practices but first let's have a look at the model view controller pattern which is the foundation of all this model view controller or short MVC is a software design pattern that divides the related program logic into three interconnected elements let me explain what every single one of these three elements stands for and how they collaborate we start with the model you could also say the data a character in our role-playing game is a model for instance it can have an ID a name hit points attributes skills and so on you as the developer know the code of your model but the user won't see your code that's where the view comes in the user probably wants to see a representation of the character in HTML plain text or amazing 3D Graphics depending on your game in other words the view is the user interface or UI to sum these two up the model updates The View and the user sees the view if the model changes let's say our character gets another skill or its hit points decreased The View will change too that's why the model always updates the view now what's up with the controller the controller does the actual work there you will find most of your code because it manipulates your data or model in our case it's the web API that will create update and delete your data since we won't have a view except the results of our calls in Swagger UI we're going to build our application in the following order first the model and then the controller and we will always jump back and forth between those two with the help of the view though the user can manipulate the data hence properties of the RPG character with buttons text fields and so on in a browser game that might be JavaScript code in essence maybe with the help of Frameworks like angular react or UJS or now Blazer webassembly this JavaScript code in turn uses the controller to do the manipulation and save these changes persistently in the database the manipulated model will update the view which is then again seen by the user and the circle starts all all over again well that sums up the MBC pattern and now we are going to build our first model the first things we need are new models we need a model for the RPG character itself and also a model for the type of RPG character this means a character class like Barbarian monk Necromancer and so on so first we create a new folder and we call this models now for the character model we will create a new class in this models folder if you have the c-sharp extensions installed you can add a new c-sharp class with a right click otherwise you just create a new file which can be done here or also with a right click of course so we right click to get to the context menu here you can see the new file entry or we go to new c-sharp and then class and we call this character all right there we are and now let's add some properties for that we can use the built-in snippet prop and then hit Tab and so we get a property and the first one should be the ID of this character now the next one is a string with a name and let's also initialize this by default with Frodo and by the way let me remove this real quick you see the warning now non-nullable property name must contain a non-null value when exiting Constructor so what we could do if we would leave it like that is we can make the string also nullable or we again set a default value and that would be Frodo in this case and this is what I was telling you here earlier in the introduction section when you enable the nullable property here then These Warnings will appear right so this just as a side note Frodo is the default name of a character so whenever we create a character well this character is first called Frodo now let's add some more these are integers first I want to set some hit points by default this value is a hundred the next then is some attributes like the strength which is 10 by default then also defense also 10 and the last one would be intelligence which is also 10 by default so the ID the name hit points strength defense and intelligence so now we will also add an RPG Class Property this means the type of the character but first we have to create a new enum for that so we can go back to the Explorer right click the project folder either choose new file or here we can directly create an enum and we call this RPG class you see it public enum now instead of a class and now here well let's add some classes feel free to add any kind of role-playing class you want to add here in this example I will use a knight's image and the cleric the most basic characters you would need I guess some melee action some magic and of course never forget the Healer all right so with that first the night then the Mage almost Mage and then the cleric and with that now we can add this property here as well so prop RPG class we call this class and by default we set this to RPG class Knights I said this tonight but again that's totally up to you of course all right the first models are ready and now let's add a new controller and make a get call to receive our first role-playing game character to add a new controller we create a new C sharp class here in the controllers folder now with the c-sharp extensions we could also already create a prepared API controller class but let's walk the necessary steps manually here first so a new class and we call this class now character controller before we can start implementing any logic we have to make this thing a proper controller now to do that first we derive from controller base so this class here and for that we also have to add the proper reference so put the cursor there and now you can press Ctrl period or you choose the the light bulb here for the quick fix menu and then we say using Microsoft asp.net core MVC now this is a base class for an MVC controller without View support as it stands here since we're building an API here we don't need View support if however we would want to add support for views we could derive from controller so this class then but in our case just make sure to add controller base and after that we have to add some attributes now the first one is the API controller attribute so up here above the class we add API controller this attribute as it states here indicates that a type and also all derived types is used to serve HTTP API responses now additionally when we add this attribute to the controller it enables several API specific features like attribute routing and automatic HTTP 400 responses if something is wrong with the model we'll get to the details later when we make use of these features now regarding attribute routing that's already the next thing we have to add So Below the API controller attribute we add the route attribute like that and that's how we are able to find the specific controller when we want to make a service call the string we add to the route attribute now in parenthesis is API and then in Brackets con controller all right this means that this controller can be accessed by first the string API then forward slash and then its name in our case it is character alright so the part of the name of the c-sharp class that comes before controller now when we have a quick look in the weather forecast controller here you see that there is no API string in the end this is totally up to you do you want to use the API string or not I like it and that's why I added here alright and now let's get into the body of our c-sharp class the first thing I'd like to add is a static mock character that we can return to the client and for that you also have to add the.net RPG models reference so let's just say private static and then a character character which is a knight and this is now a new character and again with control period we can add the using directive here using.net RPG models but since we are using C sharp 11 here and this game actually already with C sharp 10 we could also add the global keyword either we add it here so Global using and then make sure to put it on a top like that all right and this means now that the whole application knows this reference and we never have to add the using directive again now another way is to just remove it here and if you want to be a bit more organized you could either create a separate class just for the using directives or you put them all together here in the program CS for instance right so whenever you have Global usings you could put them here again this is totally up to you but you see now although the using directive is here in the program Cs and not in the character controller we still know the character class here all right and next we finally implement the get method to receive our game character so down here let's say we return an i action results because this enables us to send specific HTTP status codes back to the client together with the actual data that was requested and in this method let's just call it gets and here now we return ok and then night and with that we send the status code 200 okay now a mock character back now other options would be for instance a bad request which is then a 400 status code or what's also possible something like not found which is then the status code 404 and this makes sense if a requested character was not found for instance so let's roll back here and we return okay night so the code is implemented now let's save everything and open the terminal and test everything with.net watch run and what do we see failed to load API definition we get this Arrow when we open Swagger UI in your case it's probably the same still let's try to call our web service method via the browser so remember our route now was API and then character and here it leads to the result we want so now let's go back to Swagger here and we open the developer tools and now let's have a look at the network tab let's just reload this and we see here what does it say ambiguous HTTP method for Action actions require an explicit method HTTP method binding for Swagger or open API 3.0 so let's go back to visual studio here we actually see the error as well and now pay attention to the attribute that was added to our get method here exactly there is none so when we compare this to the weather forecast controller again you see we could have added HTTP gets right but it's not necessary for the character controller as you can see here it still works right because the web API supports naming conventions and if the name of the method starts with gets get something get Heroes get characters get RPG characters whatever it is the API assumes that the used HTTP method is also gets now apart from that we only have one get method in our controller so far so the web service knows exactly what method is requested still as we now know to help speaker out we have to add the HTTP get attribute so let's do that real quick and then we go back to Chrome all right save this should be rebuilt and now we see the method but we don't see any schemas or expected return types so let's go back to vs code one more time and let's change the I action result here to action result and then also at the type character now after saving this when we go back maybe again we get this error here in your case it might be a bit different maybe you see in the terminal that the visual studio code is asking you to restart the application because of a root edit in my case this is different so I just stop the app manually and restart it again and now hopefully yep the error is gone and we see the character here in the schemas and also the RPG class but there's still one little thing we can add looking at this enum here you see it already we only see numbers instead of the name of the RPG class same here right so we can change that by configuring the Json converter in the enamel file so let's go back again and now here we go to RPG class and we add an attribute above the enum let's start with Json converter and then with the class type of and then Json string enum converter this thing now let's also add the proper using directive here Json converter and then Json string enum converter you see it here it converts enumeration values to and from strings so with that and also the using directive here we should now see our yep there they are our RPG classes right if this is not the case for you then again maybe you have to restart the application manually but after that we should see the names of the RPG class and we can finally now test our get method so let's try this out we hit execute and we get Frodo here with the class Knights before we start with a new method let's add another mock character to the controller by replacing the single character with a list of characters because we will Implement an additional method to return that list so now instead of private static character let's make this a list of characters we call this now also characters and this is a new list of a character and here now we use the object initializer to add a new character and then also let's add another one and in here now we just say the name is same for instance all right after that we have to modify our existing get method we return the complete list of characters and so we also change the return type to an action result with a list of characters so instead of Knight first we say characters and here now this is a list of a characters all right I would say we saved this already and let's test this in Swagger and there we are let's just reload is it really yo here this is what I was talking about earlier we did a root edit so we have to re-build and restart the application here and now we can see uh that the expected result you see it here in what the brackets tell us that we expect a list now and let me try this out we hit execute we get Frodo and Sam here great so this works and now let's add another get method to return a single character and let's just return the first character of the list by default for now return type is again an action result with a character and we add the HTTP get attribute so again let's close this and let's just copy this method here and now this is again only a character we call this get single for instance and here we return the first one all right let's open the terminal and save everything and we already see something here conflicting method path combination get API character for actions they require a unique method path combination and so on all right so what does this mean this means the web API doesn't know which method to use because we have two get methods now and that's where we have to add routing attributes so let's add one to the first method and call the route get all for instance so in here we just say get all all right and I already combined the route attribute as you can see here you could actually do it like that put this down here and write get all right and then remove this thing but again you can also combine these two and then it looks like that so with the string we can decide how to get a particular method so now I saved it and we see that now the application should work and again it's time to try this out I'd say so let's have a look at survega there we are we see now our two methods and now the old one returns only one character the first one which is Frodo and we also see the expected result here and now the get all try this out hit execute we see all characters you can also see now that the request URL is really character get all so the controller name and then again our specific route that we specified so this works just fine since receiving the first RPG character of the list can get quite boring let's add an argument to our request next to get a particular RPG character we could send the ID of this certain character to the web service first we add the ID to the mock characters in the controller so the default value is zero so let's just add the ID with value 1 here to the second character Sam now it's getting interesting we add the new parameter here to the get single method and then we use a link to find the RPG character with a given ID in the list of all characters so first here this is the ID all right and now here with the method first or default followed by a Lambda expression we well we return the requested character in essence so first or defaults and then here we say C for character where the ID is the ID all right now this method now Returns the first character where the ID of the character equals the given ID now the last thing would be to add a route with a parameter to the HTTP get attribute now the parameter has to be added in curly braces so in here now first the parenthesis for the route and then here again in curly braces we just say ID and make sure that these two really match so with that our web service knows that this string here this ID this value is the actual ID parameter of the methods and that's it let's test that now again maybe we have to rebuild our application here and now let's go back to Swagger there we are we can already see that here is the ID pyramid parameter in the route all right and when we test this method now let me say try it out we have to add an ID here so let's try it with one for instance execute you see the complete request URL now so API character for the controller and now only the ID Rico's method is get and we get Sam here and with zero now we get Frodo this works just fine now before we Implement more methods in the controller let's have a look at the various HTTP request methods we will cover in this course the hypertext transfer protocol or in short HTTP defines as the mdn webdocs put it a set of request methods to indicate the desired action to be performed for a given resource to this date we can find nine request methods in the documentation the most common ones are get post put and delete these are the ones that are covered in this course because you almost always can do everything that needs to be done with only these four let's go over them shortly the get method requests a representation of the specified resource if you're using this request you should only receive data from the web service and not send data to it of course you might want to send certain characters sticks to the service like an ID or a string and the backend then grabs the proper object from the database but you won't send any objects to the service you have already seen this when you received our RPG characters sending objects to the service in turn would be done with a post request the post method is used to submit an entity to the specified resource often causing a change in state or side effects on the server this means that you might want to add a complete new RPG character to the database for instance post means to put it simply add or create a new object and do whatever you want to do with that object in the back end usually this new object will be stored in a database the put method replaces all current representations of the target resource with the request payload so this is in essence an update of the complete object if you want to change a property of an RPG character let's say just the name for example you would send the whole object to the service and it would overwrite the complete entry in the database of course there can be variations of that process but the standard way is exactly that send an object to the service that already exists and update every property of this object and finally the delete request you know it already the delete method deletes the specified resource so you send an ID to the service via the URL the service usually looks up the corresponding entry in the database and erases it if you rather want to do a soft delete meaning just set a flag so that this entry will not be shown on the client It's actually an update where you would then use the put request method but to make one thing clear nothing works automatically you have to write all the service methods by yourself and Define which HTTP request method has to be used by the client you could in fact write a service method that uses gets but then simply delete an object with the given ID it's all up to you now how do the Crut meaning create read update and delete operations match with the HTTP request methods in general maybe you know it already to create an object you would use post reading an object is done with a get call updating with put and deleting well with delete of course now that you know the most important HTTP request methods let's continue with the web API by creating a controller method to add a new character the idea behind that is that the client in our case the browser sends a Json object to the service and the service then creates a new character based on the Json data so let's start writing the methods we go down here again public action results with again a list of characters so because we will want to return all our characters so that we can directly see the change of our characters List and we call this method now at character and as parameter now we use the character type with maybe a new character here all right in the body of the function we simply add the new character to the characters List and then again we return the complete list so that we can see that the new character is part of it so we just say characters then add new character and here we return okay characters last but not least we add an attribute to this method and that would be the HTTP post attribute this time because then we are able to send data to the service so in Brackets http post now it's important to mention that the data or the Json object respectively is sent via the body of this request when we send the ID to the service earlier we did it via the URL now it's done with the body that's a crucial difference all right let's test this now we see our new post method here and opening this method already reveals an example object we could send via the body and the request content type here is properly set to application Json because we send a Json object to the web API so for our test let's just click on try it out we can remove actually most of the properties and send a new RPG character with just an ID and a name to the service so again let's just here remove this and let's say this is now id2 and here let's for instance use this name here Percival all right now let's hit execute and we see our complete list with the new character we can actually double check this in the network tab of the developer tools so let's just open this and run the method one more time we hit execute and here is our call in the headers we see this is the request URL the post the status code 200 and in the payloads we see we sent the ID and the name to our web service now just keep in mind we don't store the data persistently so when we add another character we get four in total as you can see here but as soon as we stop the web service and started again the list consists of the two initial mock characters and the added characters are gone currently we're doing all the logic of our web service calls in the controller the thing is if an application or web service is growing you might want to separate the work in two different classes or if you need to do the same work over and over again you don't want to copy your code and paste it into different controllers of course and that's where Services come in the controllers should actually be pretty simple and just forward data to the service and return the results to the client nothing else otherwise they are called fat controllers so this would be what we are currently implementing right now to be able to do that meaning just forwarding the data to the service and then return the result to the client we will inject the necessary Services into the controller so we will use dependency injection the great thing about dependency injection is that you're able to use the same service in several controllers and if you want to change the actual implementation of a service you just change one service class and you don't have to touch every single controller where you're using this service we'll come to the details when we actually implement this stuff so the client sends a request to the web API the controller takes this request calls the corresponding service the service then does all the magic like getting an RPG character from the database for instance and then the result goes back to the controller and then to the client that's it apart from that we can also introduce the idea of data transfer objects or short dtos we already have models but it's common to use these dtos for the communication between client and server the difference is this dtos are objects you won't find in the database this means they won't be mapped models in turn are a representation of a database table when we have a look at our RPG character model later on we will see a table in the database that has exactly the same Properties or Fields let's say we add the field date created or is deleted that information the user does not need to see in this case we want to save this information the database but don't want to send it back to the client that's where the dto comes in we grab the model and map information of the model to the dto there are libraries that do this for us like Auto mapper so we don't have to do this manually apart from that we can also create dtos that combine properties of several models they simply give us more freedom in what we want to return to the clients and it's not only about returning data you've already seen the example of creating a new character in that case we could use a dto as well so an object with certain information the client sends to the web service the service then grabs these information and Maps them to the actual model we'll use dtos in future lectures so that everything should become clear alright enough with the theory let's build the structure in our project now so let's Implement a clean structure now we start with creating new folders the first one is the services folder so let me close everything here real quick and now here at root we create our Services folder and in there we create the character service folder so right click new folder character service now in that folder we create the interface I character service and the corresponding implementation class character service so again right click new c-sharp interface this is now the I character service and new c-sharp class character service now the interface gets three methods in essence the methods you already know from the character controller so the first one Returns the list of characters list character and we call this now for instance get all characters then character get character by ID I know the name is now a little bit different but this is what this method does and the last one again Returns the list of characters and we call this add character again with the character parameter all right next we can add the I character service the interface to the character service implementation class and as you can see there is an error now telling us that the interface methods are not implemented now we can fix this again with the light bulb for instance and then choose Implement interface and as you can see now the methods have been generated for us but we still have to implement the bodies we can actually just jump between the character controller and the character service and copy and paste the code but remove the OK method call so where is our controller there it is and here in our get all characters method we return there's the right one we return all characters now regarding get single we return this so characters and now here the last one back to the service and again we return all characters of course you already see it here We additionally have to add the character's list so let's copy this one as well so back to the character controller copy this and now put it up here all right now regarding this warning possible null reference return we'll fix that in the very next lecture but first now regarding the character controller we have to implement some more changes first we need a Constructor we can add it with the Snippets ctor this thing we hit tab and now you see our Constructor here the parameter we want to add here is our I character service interface so I character service and let's also call this character service and now we have to add the proper reference here character service and again let me just move that to the program CS and add the global keyboard perfect all right now we know the type and then we create a new private field for the character service we can actually do that by putting the cursor there and again control period on your keyboard or using the light bulb and then we choose create and assign field character service all right now what I like to do is additionally I like to add an underscore here and here for the field name so with that now we already inject our new character service into the controller all right regarding the next implementations first let's just remove the list of characters and now regarding the bodies of the methods we have to call the character service so the code inside the brackets of ok here of the statement has to be replaced by the corresponding character's service method for get all you just write character service and then get all characters and that's it here this would be for single character service get character by ID and we also put the ID here and here now we remove this line and then say character service add character new character all right this should be everything now let's test the method to get all characters now with zubegger for instance let's just double check the console here we rebuild our application and here is Swagger again get all tried out let's close this and we hit execute and we're getting an error unable to reserve service for I character service while attempting to activate the character controller now this means the web API wants to inject the I character service but doesn't know which implementation class it should use so we better tell it now to do that we go back to visual studio and then to the program Cs and in here now we add a new line build a services and scoped and then I character service and then character service like that and the using directive is not necessary because we already edited here with the global keyword already so now the web API knows that it has to use the character service class whenever a controller wants to inject the I character service in essence we registered the character service here the beauty of that is that whenever we want to change that and use another implementation class so not the character service we just change this line and we're done you don't have to change anything in the controllers injecting the I character service so for instance if you would write a character service too you just change it here like that and you're done now with ADD scope to be create a new instance of the requested service for every request that comes in there are also the methods at transient and add Singleton so for instance add transient this one provides a new instance to every controller and to every service even within the same request and then we also got Singleton this one creates only one instance that is used for every request alright we only need add sculpt here so when we test this now we shouldn't get an error anymore so let's open Swagger one more time let's just refresh this get all to try this out hit execute and we still get the error and if this is the case for you as well one more tip let's just rebuild this again there we are we try this out one more time and now we get all our Knights Frodo and Sam this is what we expected all right now next maybe you've seen this here again let's fix this little warning here you see the warning here and it's telling us possible now reference return meaning that we actually want to return a character object a non-nutable object here but first or default might return null meaning that this statement here might result in will something that's not there right a character that does not exist with the given ID so this means that it is possible we return null now this does match with this return type here there are several ways to fix this we could for instance just say here we expect a character that is nullable but then we get another warning here what you can also do is we can use the null for giving character we will also use this thing later in the course in other situations or you just check for this right so what you can do now is we say VAR character is characters with the first or default and now it could be that the character is actually now and if the character now is not now we just say return this character everything went fine but otherwise what we can do is we just throw an exception throw new exception with character not found all right so now we save this and we can already test that in Swagger so let's say here we try this out with ID 1 for instance everything is fine but what about id2 now character not found we get an exception all right this might not be the best solution but I think for now this is totally sufficient and we'll talk about other Solutions later what are asynchronous calls and why should you bother put simply with a synchronous call you would give a task to a threat like fetching data from a database and the thread waits for this task to be finished and wouldn't do anything else until the task is done now with an asynchronous call This Thread wouldn't wait at all instead it would be open for new tasks and as soon as the other task for instance fetching data from the database is done it would grab the data and return it in our current application this isn't really necessary we have no database calls that take lots of time our tasks are done in milliseconds additionally it's very likely that you have more than one thread available for your application so even if one thread is waiting for a task another thread can do another task but in large applications with lots of users it can really happen that all threads are busy in this case your app won't respond to a request anymore which leads to a terrible user experience and you may even lose users or even paying customers because of this so this can lead to serious trouble and that's why it doesn't hurt to know this and also implement it early in this project although the methods in the character service here won't do anything asynchronous they will later on when we fetch data from the database so let's start off with the I character service interface here we just add the task type to our return types and this would look like this task and that's already it right so let's just copy this task here and here and also add the Cur the angle brackets of course and after that we switch to the character service and also add the task return type so that would be here task and here and also here additionally we add the keyword async to the methods so in front of the return type we add async all right so here and here as well now the arrows are gone we get this little warning here that this async method lacks await operators meaning that it doesn't really do anything asynchronous now don't mind These Warnings for now we've got asynchronous methods the code will still be executed synchronously but when we add Entity framework with database queries later on we'll have asynchronous calls last but not least is now the character controller so let's move to this thing here again we add the task type and the async keyword to every method so here this would be async task also here let me just copy this all right at the closing bracket and here as well and now additionally we add the keyword await to the actual service call and that's how we call an asynchronous method so here now we say await and you see the warning here now is gone because we really call an asynchronous method await and also here oh wait all right that's it making test cards with swagger will return exactly the same results as before again please don't mind that making all these methods asynchronous is not necessary for such a small project but you're here to learn something I guess so that's how you should do it with large applications another practice you might come along in professional projects is to return a wrapper object to the client with every service call advantages are that you can add additional information to the returning result like a success or exception message the front end is able to react to this additional information and read the actual data with the help of HTTP interceptors for instance and we can make use of generics to use the correct types let's add that object to our models first so in our models folder here we create a new class and we call this thing service response all right now the actual class name would be service response and then in angle brackets T where T is the actual type of the data we want to return and then we can add some properties right so let's add prop and then T and let's make this also nullable and this will be our data and then we also add a Boolean flag you can call this either is successful or success for instance by default let's just set this to true and after that one more thing I would like to add is a string for a message and by default this is simply an empty string so the data of type T is well the actual data like the RPG characters with the success property we can tell the front end if everything went right and the message property can be used to send a nice explanatory message for instance in case of an error similar to the asynchronous implementations we don't really need that now but you will thank me later when you're working on bigger projects where these kinds of things come in quite handy for instance when you catch exceptions in a try catch block a service response like this might help you anyways to make use of our new service response we have to modify the return types of our character service and I character service methods again sorry about that so let's start with the interface in here now we simply add the service response class so actually now we return the task of a service response right and then the type is a list of character and the same here service response and last one service response of course we also have to make changes to the actual implementations of the methods so now we go here and we get some more space and again we add service response here as well service response and also down here all right now again of course we have to also change the bodies here as you can see now we've got errors we do not want to return the characters List now we want to return a service response so in general we create a new service response object in every method and then set the data property accordingly so for instance let's start with the add character method here VAR called the service response and this is now a new service response with a list of character now we add the character to the characters List and here now we can say service response data is the character's list and down here we return the service response all right so again we just Define the service response first we do whatever we want to do with the characters list for instance and then we set the data property to the characters List and return the service response in the end and with the other methods we pretty much do the same so let's just copy this line here again put it here and here now we say that our service response data again are the characters and again we just return the service response and now here again we've got the service response defined actually we can get the character here and even if it is null doesn't really matter because as you can see in our definition here the property data is of a nullable type right so this time we do not get a warning in that case we would really just return null if the character is not so we set again the service response data to character and then again return the service response and of course here this is a typical copy paste error we do it like that and now it works all right let's save that and last not least is the character controller there we also have to make some changes so that we see the proper changes also in Swagger UI so let's just save everything and now let's move on to our character controller here and here we now again want to return a service response all right and let me just again copy service response add it down here and here as well all right now let's save everything and I would say it's time to test this if you get some errors feel free to well stop the application and run it again but then we already see a first look here at Swagger it shows us two new types we get a service response for a single character here and we also get one for a list of characters right so here in the data you see this is actually a list of characters see it here with the with the bracket and here we only get one character for the data object and of course also the the success value and the message now apart from that the results will also look a bit different now let's get all characters here for instance so we try this out hit execute and this is now the result we get the data property here data object which is again the list of characters and then also success is set to true and an empty message the same of course here for the I what for get character by ID so here we get Sam in the data and now regarding adding a new character let's just leave it at that we hit execute and we get three characters now in our data object here all right so you see that our characters are wrapped in our service response the front end could react to the new properties and provide a smooth user experience with toast notifications or something similar instead of presenting complex exception messages in the console or worse a frozen application in case of an error you already heard about them now it's time to use dtos first things first let's create a new folder here at root level and we call this now dtos all right in here now similar to the services we create another folder and create and call it character alright so here we will put all our dtos for the RPG characters as already mentioned the idea behind dtos is that you've got smaller objects that do not consist of every property of the corresponding model when we create a database table for our RPG characters later in this course we could add properties like the created and modified date or a flag for the soft deletion of that character and we don't want to send this data to the clients so we map certain properties of the model to the dto that would be the case of returning data to the client but it also works the other way around we already created a new RPG character by only providing an ID and a name so why not use a type that only consists of these two properties or other properties we want to use this is even more important when you build a front-end that should use a specific type of the creation of a new character at the moment we have these two cases receiving RPG characters from the server and sending a new character to the server so let's create two classes called get character dto and add character dto so in here now in the dto's character folder we create these two new c-sharp classes get character dto and then also a new class at character dto another option to name these things would be something like like add character request dto for instance or just add character request and in here you could call this add character response dto this is a nice convention if you want to use it because that way you can already see that this is a dto for the response for getting that stuff and sending it to the client and add character request dto for instance would be a nice name where you directly see this is used to send this dto to the server but this just a little side note now regarding the get character dto here it should look exactly the same as the character model for now so let's just go here and copy this get character DDO and paste it here I know it does not seem to make sense but I don't want you to be overwhelmed by implementing anything Entity framework related at the same time so adding the dtos is a good preparation now the add character dto looks a little bit different let's say we want to send every property but the ID to the service so we can actually again copy the properties of the model but we remove the i d here like that all right and now our dtos are ready and so we can use them in our controller and service methods so again we go to the I character service and instead of the character type we now return get character dto so here this would be get character dto copy this again and instead of the character here in the add character method we use the add character dto like that all right so we switched the model and now use the dtos of course we need the using directive here and again totally up to you but maybe you also wanna set this to the put it into the program CS and add the global keyboard here let's save that now and the warnings or the error messages are gone now of course the same changes have to be made here in the implementation class the character service and then also the character controller so here we replace character with get a character dto and we do that here as well and here and also in the service response here it's the same thing and now also here we use the add character dto all right we already see some errors but more about that in a sec let's just make the change also to the character controller here so that would be the get character dto same here and same here and here it's the add character in dto alright so these are the changes in the controller and now again here these errors you see that Visual Studio code is not happy with that change the types here they do not really match you see actually this is expecting a get character dto list but here we've got the list of characters so not matching types and that's where we have to map the dtos with the model it's time for automapper we could map the objects manually by creating a new instance of the necessary class and then setting every property one by one but the idea behind Auto mapper is that it's doing exactly that for us on the fly but first we have to install auto mapper of course now as you can see here there's a package available on nuget.org automapa extensions Microsoft dependency injection so if you want you can Google for this package and then just copy this complete line you do not need the version here we just installed the latest package so please you do not have to specify the version if you want of course you can but this is not necessary so we go back to visual studio we stop the app maybe get some space here and now I just paste it but of course for you just enter.net add package and then automapa.extensions.microsoft dot dependency injection and then we hit return all right and when the installation is done you'll see this entry in our project file right here now let's get some space again there it is Auto map extensions Microsoft dependency injection version 12 in my case by the time of recording this pretty close to the release of net 7. all right now after the installation we jump to the program CS first because here now we have to register automapa and to do that we can do that right here or maybe on top of the service registrations because there will be more services so in here now we type Builder services and then add Auto mapper and then type off and then the class we're currently in which is the program class and from that assembly like that and you're done automepper is now registered now to be able to use the mapping of automapper we now need an instance of the mapper in our service so we go to the character service maybe save everything here and in the character service now we add a Constructor and then inject the I mapper interface from Auto mapper so similar to the controller we also need a Constructor here as well you can type ctlr hit Tab and now here we write I mapper call this thing mapper as you can see we need another using directive Auto mapper and now since I am lazy or let me just say I leave this up to you do you want to use the local usings here do you want to use the global mappings and or do you want to move them to the project class I will sometimes just leave them here it's not the best way of course so please think about that for a moment what is more organized what is better in your case but just so you can see you can of course develop your application like that as well you just add the using directive at the global keyword and then this thing is known throughout the whole project because we will need automepper in other lectures of this course as well Okay so we've got the uh the reference and now again we create our private field here we add the underscore and we've got Auto mapper so now we can use the mapper to set the correct types to the data property of our service response maybe we can start down here with the get character by ID method so using the map function we first decide in angle brackets which type the value should be mapped to so again first the mapper similar to the character service in the character controller right here we now use the mapper and now the map function and again in angle brackets we say we want to get character dto all right and now we need a parameter which is the actual object that will be mapped so again we choose the mapper here with the map function and first in angle brackets we decide which type the value here should be mapped to and as a parameter this will then be the actual object that will be mapped and now we do not have an error anymore this thing now is a get character dto now the changes for the other two methods are pretty straightforward in the add character method for instance we first map the new character so we do it like that mapper map character and this is now the new character object so in this case it's the other way around we map the add character dto to the character and how to map a whole list in one line we use the select method of link so this would look like that we've got our characters List then select and then here with a Lambda expression again for every character here again we choose the mapper object map we turn this into a get character dto and the actual object now is the current character and in the end we turn this to a list why a list well select returns an i innumerable and we want an actual list so this is now a list of the get character dto and now finally the get all characters methods we map every single RPG character of the characters List with select again similar to the add character method so select C mapa map get character dto and in the end again we turn this into a list all right let's test this now we saved everything and run this with.net watch run again let's try the get all route we try this out we hit execute and we're getting an error missing type map configuration or unsupported mapping so Auto mapper does not know how to map character into a get character dto now you might ask it's called Auto mapper so why isn't this working automatically well we have to configure one more thing but then I promise automepper is working fine we have to create maps for the mappings and this is organized in profiles you could create a profile for every mapping but let's spare the hassle and just create one class for all profiles for now so back to visual studio and now at root level let's create a new c-sharp class and we call this thing also mapper profile all right and this class now derives from profile if you haven't already make sure to add the auto mapper using directive now and regarding the implementation we need a Constructor with no parameter and then create a map for the necessary mapping so ctor it is and we have no parameters and now down here we say create map and then character to get character dto all right so this is not the map to turn a character or map a character object into a get character dto everything is saved we restart the application let's see if this already worked go to get all tried out hit execute and now we are getting our characters what about a single one try this out we get Sam and what about adding a character try this out hit execute still getting an error so we have to create another map see it here add character dto to character so let's go back to visual studio and in here now we say create map and then add character dto character all right one more test there we are we try to add a new character we hit execute and maybe we have to restart the application ourselves but then let's just see try to add a new character it executes and we see the third one here now we've got one little problem here when we see this object the add character dto this is now suggested by Swagger you see it Swagger knows that we have no ID here now this is different right problem is the ID here now is zero should be three actually right now that's because the add character dto does not provide any ID of course and that's exactly what we wanted but still let's fix this real quick by generating a proper ID ourselves so let's go back to the add character method and the character service here there we are and here we first create a new character all right so bar character and this is now actually our new character here and then we set the correct ID by finding the current maximum value in the characters List and we increase it by one so here now we say character ID is characters Max 4 so the maximum value for the ID of all characters in the list and you know we just say one and after that we again just add our character object here and we're done so now when everything is saved and hopefully properly restarted we add another character hit execute and now we see that the ID is two now this is of course unfortunate because of the re the the hot reload we still have this character here but let's make this one final test here we start this one more time manually and now when we get all we get two characters with ID 0 and 1. and now in our post method we add the third character hit execute and now we've got ID 0 1 and 2. great so without even sending an ID the new RPG character gets the correct one later when we use Entity framework it will generate the proper ID by itself alright we're done here I know it was a lot and maybe way too much implementation for such a small project but in large real world applications that's how it's done to modify or update an RPG character we have to add a new method to the I character interface the character service class and the character controller so let's start with the interface and here now we add a new method let me just copy this here so we call this now updates character the return type is a get character GTO like that all right because I want to return the character so that we can see the changes directly and the parameter is actually a new dto we will call this thing update character dto so of course we have to add this dto real quick so now in our dto folder here add a new c-sharp class update character dto and in here now again we can copy a lot actually and again it's actually exactly the same as the get character dto for now new thing is maybe when we compared to the add character dto here that we actually want the ID right so now we're sending something to the server but still we need the ID in this request object all right so now we implement the method in the character service let's go here and we can implement it automatically actually so where is it there it is and again we will start with a service response and then we try to find the RPG character with the given ID of the updated character objects which is as I see it here right now not properly named so this should actually be the updated character and not the new character so update it character it is nice now it's correct and after that we override almost every property of this RPG character one by one meaning the name hit points strength defense intelligence and the class all right let's do that first real quick we add the async keyboard here and now we start with our service response so bar service response is a new service response with the get character dto now the character character is characters first or in default and then where the character ID equals now the updated character id right so from our request object we grab the ID and after that again we just map everything manually so the character name is the updated character name and now let me just copy everything here so we will need the hit points and hit points here as well and then the strength defense intelligence and the class so this would be the strength strength defense defense intelligence intelligence and the class in the ends all right so now regarding the data we say service response data is now mappa map get character dto and then character not the class of course it's the variable here or objects and in the end we return the service response alright now we have this little warning here again that we've got a possible now reference but let's deal with that in a minute for now let's move on to the character controller and write our update character method in essence we can just copy this thing here the add character methods we turn our attribute now to http put very important of course we call this updates character in here now it's an update character dto this is the updated character and we return update character with the updated character here all right I would say it's time for Swagger we save everything maybe we restart everything manually there we are and maybe first let's get all RPG characters for reference so get all try this out we hit execute and there they are all right now we can run the update call there it is and let's just try it out with all these default values we hit execute and this already seems to work everything here is replaced now let's have a look at our characters again we hit execute yep the character with ID 0 is not Frodo anymore this guy is now called string has no hit points and so on and still is by default a knight so it's good that this will be changed again when we restart the application but again keep in mind that every single property has been updated this means that the strength defense and so on will be overridden even though we did not send a value for these properties with the body if you would run another update now and leave the RPG class for instance Frodo would be turned into a knight in any case because that's the default value so you have to pay attention to how you design your front end in this case do you want to update single Properties or all at once by receiving the current values of the character and save them back again even though they did not change anyways that was just a side note now let's try to update a character that doesn't exist so again back to our put method here and let's change the ID for instance to 2 and see what happens it execute and there it is another reference exception object reference not set to an instance of an object we have two options now either we catch that exception with a try catch block or we just check if we find a character in the characters List or we do both so let's start with the try catch block maybe back to visual studio and back to our character service right here we open our try block that and down here comes the catch like that all right and in the catch block here now what we do is actually we only set the service response success to false and the service response message to the actual exception message so service response not the class here this is what I was looking for success is set to false and the service response I know I made a little mistake up here so let me remove this put it up here now it should work the message is exception message all right let's save that let me just restart the app again and here now let me try this out one more time id2 it executes and we get this response body now and this is our exception message successes false data is null all right this works and it's already okay I guess but what about a custom exception message and apart from that I'd like to finally get rid of this little warning here so let's add another change we just check if the characters actually null and then if so we throw an exception manually so here now we say if character is now we say Throw new exception and regarding the message we say character with ID and now the updated character id not found all right let's try this again put try it out execute character with id2 not found much better don't you think now a possible front end can work with that maybe still another message would be more suitable for a user alternatively we can add a slight modification to the character controller actually you see we're still getting the status code 200 okay where the character wasn't found so maybe we can also return a 404 not found response so let's go back to the character controller and in here now we add a little bit more logic so we first just get the response of the update character method here and then we check if the data is null and if so we return are not found and otherwise we return okay all right so let me just move this here so bar response is now this and if now the response data is null we say return not found response and otherwise we simply return the response here as well all right Let's test this one more time put try this out id2 execute and now it's 404 not found as you can see here as well feel free to play around with that for instance you do not have to use the message of the service response only in case of an error what about a success message like your character has been saved anyways let's move on and remove an RPG character there's still one little thing I want to show you before we remove a character with the leads because it was asked a lot by you guys what about updating the character with automapa of course this is also an option so what we could do also is for instance something like mappa map and then character and then updated character all right so we just map the updated character to the character object another option would be to use the map function and then probably already tells you here object Source well no there's an overload it would be updated character character so this means we map this updated character to the character object and if you choose this way then you would also have to create another map so in here now and the um automatic profile we would then add create map updates its updates character dto and then also character all right so these are other options for you just wanted to show you this I will discard these changes now and then now move on to delete a character to delete an RPG character again we have to make modifications to the I character service interface the character service and the character controller so again let's start in the interface here and here now again we add a new method maybe we can return the list of all characters to see if it was really removed and we call this now delete character with an ID as a parameter and now let's already move to the character's service we implement the interface where's the method there it is and actually we can copy the code of the update character and just make some changes so let me just grab everything from here and now here the delete character methods so first the async keyword very important and then we fix the service response because now we return a list of get character dtos instead of first or default we can use First now the difference is that first or default will return null if no matching entity was found and first throws an exception directly the exception message is not the best for a user but for learning purposes let's still make use of that now if however a character was found we remove it from the list so first let's check if this character was found then remove this and say characters remove character and in the end we return a mapped list of the remaining characters similar to the expression in the get all characters method here so let's just say characters selects and then we do the mapping to list all right that's already it for the delete character method in the service and now in the controller right here it's actually a combination of the get signal and update character method so maybe we can copy this all right now again really important of course the attribute here we choose the delete HTTP request method we need a parameter again that's correct we can call this delete or delete character for instance and the body is almost the same as in here in the update character method so so let me just copy this We Run The delete character method with the ID if the data is now be returned or not found otherwise we simply return the response alright let's save everything and let's start the application all right we see the delete method already now let's try it out we choose ID 0 for instance we hit execute we only see Sam so this already works now what about another ID that doesn't exist like two we hit execute we get a not found but the message is sequence contains no matching elements now why is that this is again the difference between first and first or default so this does in this case not really make sense if you change it back to first or default save this and maybe it's reloading by itself then we try this one more time try it out with nope not put method of course the delete method try this with ID 0 hit execute character with any zero not found you see we still got both characters because of a hot re uh we got the change because of the hard reload we did not rebuild the whole application so again when we have a look here we see only Sam and it already worked with ID 0 so with id2 of course we see the proper or our message here in this case but with the one now everything is deleted and we've got no Heroes any more perfect so this works just fine our web API with all crud operations is done it's time to save the data in a database now with Entity framework and SQL Server congratulations a lot has happened in the past lectures you created your first web API with.net with all crud operations meaning create read update and delete you learned what HTTP request methods are and used get postput and delete for your web service calls Additionally you now know what the model view controller or MVC design pattern is and how it works and you learned some Concepts and practices used in large real world applications like a clean structure of your web API with dependency injection asynchronous calls a proper service response and data transfer objects you're definitely ready for the Entity framework section Welcome to The Entity framework section in this section you will learn how to connect your web API to a database and save all the data you're creating in database tables we will utilize Entity framework 7 internally still called Entity framework core to complete all crud operations but this time your changes will be persistent so the RPG characters we're going to add or update will still be there and the changes will still have an effect even when we stop the web servers from running we will install and use Microsoft SQL Server Express for the database and create the necessary tables with the help of code first migrations all our service calls will finally be asynchronous so without further Ado let's start what does object relational mapping actually mean it really is quite simple so far we created our RPG characters as models or classes us in our code these models consist of several properties the RPG character has an ID a name hit points and so on in essence this whole thing is the objects databases like SQL Server sqlite MySQL mariadb and many more are relational databases and use relational database systems they consist of tables to save data and these tables can have relationships with each other it's exactly the same with our models so far we only have one model but as soon as we add skills for instance we have another model that can be related to our RPG characters a character has certain skills like throwing Fireballs as a mage you will find this relationship in the database as well there will be a table for characters another one for skills and another one for the relationship between characters and skills but that's just one example in the past developers had to build these relationships manually in the database with an object relational mapper-like Entity framework this is history Entity framework grabs our models and knows what tables have to be created if the models change Entity framework changes the tables and the relationships in the database basically you'll never have to look at the database tables and that's also the magic behind code first migration you build your code your models first and then Entity framework creates the corresponding database there's also the option to build the database tables first and let Entity framework build the models but the first way is more common and also more fun in my opinion alright enough with the theory let's install everything and then write some code first things first we're going to need some packages here that we want to install and as you can see here already on the screen I'm on nuget and these this is the first package that you want to install which is Microsoft NT framework core and since we're going to use SQL Server we will also need a corresponding package for SQL Server which is then the provider for this database and after that we will also need the package design but one step after another so please either go to this page or just type this in with me you do not have to specify the latest version here in our case we've got 7.0.0 so this is really really new and shiny stuff with.net7 so let's go back to our project here in vs code I'm opening the terminal here and now we just enter.net add package and then Microsoft Entity framework core and just install this thing and right after that we simply add SQL server and then the last one is again the design package which enables the.net EF commands on a specific project all right now let's just double check here in our project file now we should see entity from a core design and SQL Server alright now the next step would be installing the actual Entity framework tool that allows us to use Entity framework migrations now to do that again we open the terminal and in here now we enter dot net and then tool then install and then I want to install this globally so dash dash Global and then that would be dotnet EF and in my case it's telling me.netif is already installed so what I can do now here is either I can enter update or first I'm just uninstalling this thing uninstall to show you guys see that version 7.0.0 was successfully uninstalled and now what I can do of course I can install it back again and now it's telling me this thing is installed and now with net EF I can check that there it is these are the HD framework core.net command line tools version 7.0.0 please note the side note here it's internally still called Entity framework core right we are working with Entity framework 7 here internally it's still core and I think this will never change well at least in the near future but that's just a side note and now everything is available in our project to work with Entity framework so the next step now would be installing SQL Server now the easiest way to get SQL server or SQL Server Express which is the free version that we want to use here in this tutorial in this online course the easiest way is simply Google for SQL server and then already the first hit should be the right one SQL Server downloads and then you scroll a bit further down and here you get the express version as you can see here it's a free edition of secret server ideal for development and production for desktop web and small server applications so please download this thing I have already got it installed and I think you know how to install this thing on your machine and when you did this you can also you you will see in the installer that it suggests installing also the SQL Server management Studio here SQL Server management Studio it should be so here you can see the first hit again download SQL Server management studio and when we go there we this is really big we should see here is the free download for SQL Server management studio so this is a great tool in my opinion to have a look at your database make some changes and so on so please do that and when you're done let's continue with the next lecture to make use of Entity framework the first thing we need is a data context for that we create a new folder here at root level and we call this folder now data and in here now we create a new c-sharp class that we can call a data context for instance now this class inherits from a Microsoft Entity framework core and then DB contacts and you see this is why we needed this package so make sure to also add the corresponding using directive here again we can actually make this Global because we will need this thing a couple of times so let's move this to the program CS there we are paste it here save it here as well and now we should know this package awesome all right now as you can see here an instance of the DB context represents a session with the database this means we can use this instance to query the database and save all the changes to our RPG characters this description here also says that the DB context is a combination of the unit of work and the repository pattern so essentially it provides an abstraction of our data so that we are able to work with the data directly we can reuse the database access code and add remove update and select our data with straightforward methods we will see how this is done in detail very soon so we've got our data context class now we have to add a Constructor again we can use this built-in snippet here data context there it is and the parameter will be of type DB context options and then our data context and let's call this thing also options and we also have to use the base Constructor here so base with options as well last but not least we have to add a so-called DB sets in particular a DB set of the type character so we do it like that it is a property so what we do is we type DB set and then character so basically with this DB set now we are able to query and save our RPG characters now the name of this DB set will be the name of the corresponding database table I think that characters is a good choice then usually you would just pluralize the name of the entity so whenever you want to see a representation of your model in the database you have to add a DB set of this model and that's how Entity framework knows what tables it should create now you see this little warning here again what you can do is instead of using the getter and the setter here we just say this is now a set of character and this should also work then because as you can see here it creates a DB set of character that can be used to query and save instances of a character so it already returns a set for the given entity type as you can see here all right we're done here so let's continue with the next lecture the connection string and adding the DB context before we can start with the actual migration we have to provide a connection string and add the DB context to the service collection of our application now the connection string this thing can be added in the app settings Json file here we can ignore the app settings development Json since we don't make any differences between those two files for now so in this file now in the app settings Json file we add a new section on top here and we call this section connection strings already suggested here that's great and this exact name is important because it's a convention we can use to register the DB context in the program CS in a minute now in this new section we Define the actual connection string so this name doesn't follow any convention but usually you would call this the default connection all right now the actual string can be tricky at times if you have installed SQL Server expressed earlier then maybe there was a certain string mentioned there so you can use this one or you make little changes to this one that was suggested for you or you just enter a new one either way you have to check the name of your database server in my case SQL Server is installed locally so it's either a local host and then SQL Express or just a period and then backslash backslash SQL Express so again yours can be different but after the server then we add the database name so let's just let's just type this in I would suggest so again in quotation marks first the server and again in my case this would be SQL Express all right after that then the database name so that would be database and then maybe dotnet RPG for net role playing game and that's how Entity framework will call our database if it doesn't exist yet and after that we add trusted connection true and now new with.net7 and Entity framework seven we also have to add trusts server certificate and set this also to true all right so this should be it we've got our server which is a period backslash backslash SQL Express then the database is dot net Dash RPG trusted connection through and then trust server certificate also set to True again trust server certificate is new with.net7 and entry framework 7 if you do not add this thing we'll get an error as soon as we try to run our migrations all right so this is our connection string now we have to access the string in the program CS so we save this and now in our program CS we can actually right on top here at Builder services and then add DB contact so we're registering our database context here type again is data context almost this one here and again we need the using directive here let's just also add the global keyboard all right this looks great now and in here now we add a parameter so we add a Lambda expression with the function use SQL Server which configures our context to connect to SQL Server database and this method then in turn finally takes the connection string all right let's call this parameter options and now in a new line we say options use SQL Server and here now we say Builder configuration and then get connection string you see now the convention makes sense because with that you're accessing the connection strings section of our app settings Json file and here we enter the name default connection and you're done so again real quick here now in the app settings Json you see this connection strings the name is default connection we can copy and paste this actually so this is now the string we need here and with that we just save everything and we're done with our configuration and next up we start our first migration all right now let's open the terminal and here first let's have a look at the options of the.net EF command so in the terminal we enter dotnet EF and then Dash h so here you can see three commands database commands to manage the database DB context commands to manage DB context types and migrations commands to manage migrations in fact we only need two of them and these would be database and migrations so to run the first migration we type dotnet EF and then migrations ads and then for instance initial create because this is our initial migration so with this command now we add a new migration we call it initial create you could also call it initial or whatever you like because in this case now it's our initial migration that will create the database and all tables so let's just run this make sure that the app is not running we hit return we'll start it build succeeded and we're done and now in the file explorer we should see a new folder which is the migrations folder so now these files are used by Entity framework so that it knows what it should do with this migration they provide information about your tables and Fields that Entity framework uses to build your database so let's have a look at this first file here you see it consists of an app method here and also a down method down here now in the app method you can see what's going to happen when we commit this migration Entity framework will create the table called characters with the columns and also set the primary key ID if you want to go a bit deeper again you can see here characters is exactly the name we have entered in our data context for this DB set right so these match now this is the table name for our characters table and then again you see we've got the ID the name hit points and so on with the class also so these are actually the properties of our character model and the ID this is done automatically by Entity framework ID is simply the primary key this is also a convention now the down method this is pretty simple this one is used to roll back a migration so it simply deletes the character's table so now I would say we run this migration now in the terminal we enter dotnet EF database updates and with this command now Entity framework is going to run the last migration and so create the new table and not only the new table with this specific migration here it also creates the database now we're already done here you see the command create table and again I suggest you go a bit deeper just have a look here you can also see create database.net RPG then the internal table used only by Entity framework we do not have to look at this thing this one is used for the migrations history not interesting for us it can be interesting if you really run want to play around rollback several migrations then maybe you have to change it change something here I don't really recommend it but sometimes this is necessary hopefully not in your case but for our case now this looks promising here so now we can have a look at SQL Server management Studio there we are already and now let's just refresh the whole database and in here now voila there's our.net RPG database with the table characters and the corresponding columns isn't that great now we can also right click and then say edit top 200 rows but since this table is empty I would say we changed that in the next lecture now the very first thing we have to do to be able to access our RPG characters is to get access to the data context we make use of dependency injection for that and add the contacts to the Constructor of our character service again here in the Constructor I'm already here in the character service we add now our data context call this thing context and again we initialize this field from a parameter we already got the underscore here now by the way this is because I used this suggested action here it says extract and then initialize field from parameter if you would use something where you see the light bulb here chances are that you would again see the this keyword here not the case if you choose the other entry in the context menu if it is available I have to mention that if it is available all right but this again just a side note so we've got our data context injected and now with that the context is available everywhere in our character servers so in the get all characters method for instance what we can do here now is first we add a new line to get the characters from the database so here we say VAR DB characters is a weight context and our characters so this is how we get access to our characters table and then simply to list async all right and that's it and now instead of selecting the static characters here we just use our new DB characters again use the select method to map all the characters because this is a list still of the character class here and we're done these are all the necessary changes again really important we inject the the data context up here in our Constructor we've got our database context here and then in the method which whatever method you want to use we first access our characters with contacts and then characters this is the table our database set characters where we will find every character and then turn this into a list and with that then we have a list of characters and in the end you already know that we just mapped them to a get a character dto every single one and then return the service response all right I would say we run this now so dot net watch run it is there is Swagger and now pay attention we try this out we hit execute and we get no character back of course because there is no character in the characters table in the database yet so let's just add one in SQL Server management studio and there we are and here now we do not have to enter any ID just the name the hit points and so on and then confirm the new entry with enter so I would say again we just enter Florida here for instance with 100 hit points everything else is just 10 and the class now would be one for a night and here Sam again with a hundred ten ten ten and also one for the night everything is already saved now pay attention here we do not have to rebuild or restart our application here we don't have to reload the page we just hit execute and there are our Mighty Knights and you can see that the ID here is also correct one and two same thing here in the database now receiving a single RPG is quite similar so let's just go back to the get character by ID method here and then instead of this character now let's just say again this is our DB character for database character and here now we wanna get this one by calling a weight and then context characters and then first or default async so with that we get the character from database and you know we use this database character and again we are done and by the way you see that these yellow lines have disappeared because we are finally using asynchronous methods cool isn't it anyways to test the new get character by the method let's go back to zweger it has been reloaded I hope it is the state is correct so let's try this now we hit execute with a proper ID of course so enter one we get Frodo and with two we get Sam awesome now let's add a character to our characters table next
Info
Channel: Patrick God
Views: 88,768
Rating: undefined out of 5
Keywords:
Id: 9zJn3a7L1uE
Channel Id: undefined
Length: 140min 13sec (8413 seconds)
Published: Tue Dec 13 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.