🚀 .NET Core 3.1 Web API & Entity Framework Core Jumpstart

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
dotnet core is getting better and better and more important in the web development world nowadays almost every request I get for new web development projects is asking for knowledge internet core including web api and entity framework core so knowing the fundamentals of back-end web development with dotnet core can be highly beneficial to your career and that's where this course comes in in a short period of time you will learn how to set up a Web API make restful calls to this Web API and also safe data persistently with entity framework core code first migration as sequel server database and all three types of relationships in this database we will get right to the point you will see every single step of writing the necessary code and by the end of this course you will have what it takes to say yes to all the dotnet core project requests from any recruiter the only tools you need in the beginning are Visual Studio code and postman both are available for free we will use Visual Studio code for our implementations and postman to make calls to the Web API both tools are available for Windows Mac OS and Linux and since dotnet core is cross-platform you can follow this course on any of these operating systems later we will also utilize sequel server Express and the sequel server management studio to manage our database these are also available for free the backend application we are going to build is a small text-based role-playing game where different users can register we're going to use JSON web tokens for authentication and create their own characters like a mage or a knight add some skills and a weapon and also let the characters fight against each other to see who is the best of them all my name is Patrick and I will be your instructor in this course I'm a web developer for over a decade now I have worked for big corporations and small teams as an employee and as a contractor and I just love to see the way Microsoft is going with dotnet and how important it gets day by day so I hope you're ready for your new skills and your new projects and looking forward to seeing you in the course welcome and thank you very much for joining the dotnet Core 3.1 Web API and entity framework Core jumpstart course this course is meant to teach you dotnet core skills fast and efficiently so you will be ready to tackle any upcoming project with ease this is what you will learn in the next couple of hours in this chapter you will prepare your machine with the necessary tools Visual Studio code postman and the.net core SDK and then you will already create your first web api with dotnet core and even make your first api call after that you can create a git repository for your project if you want to then we dive deep into the Web API you'll learn about the model-view-controller pattern and best practices for a clean web api structure and clean code we'll get to asynchronous implementations with async and await used data transfer objects we will cover all crud operations meaning create read update and delete with the mostly used HTTP methods get post put and delete we'll get to the details later the following chapter provides persistence with entity framework core entity framework is an object relational mapper that will save all our changes in a sequel server database we will utilize the code first migration to do that and again implement all crud operations then we'll cover authentication users will be able to register and log in and only see their related entities we will use cryptography to hash the passwords and utilize JSON web tokens to authenticate the user with every subsequent web service call further on we'll have a look at all types of relationships in a database that's one-to-one one-to-many and many-to-many relationships each one needs its own kind of implementation and finally since in this example project you will create some role-playing characters we will let them fight against each other all by themselves by choosing their weapon or one of their skills in the end one character will have the most victories and that's what we want to display all right you see there's a lot to learn let's start as soon as the dotnet core SDK Visual Studio code and postman is installed we can already create our first dotnet core application which will be a Web API right away to start I created a new folder called dotnet - RPG for dotnet role-playing game open the folder in Visual Studio code I assume you're already a bit familiar with Visual Studio code if not feel free to have a look around while you're doing that it might also be a good idea to install certain extensions first c-sharp for visual studio code by microsoft itself this extension will also be suggested by Visual Studio code as soon as you create your first c-sharp application it includes editing support syntax highlighting intellisense go to definition find our references just have a look pretty useful stuff next is c-sharp extensions by j.chan n' as the description says it might speed up the development workflow by adding some entries to the context menu like adding a new c shop class or interface and the last one already is one of my personal favourites the material icon theme this one simply provides lots and lots of cute icons but now let's create our Web API we open a new terminal window and then let's have a look at what the dotnet command provides with adding a - age you see all the available commands the one that's really interesting for us right now is the new commands which creates a new dotnet project but you also get the run command - well run our application and also the watch command which can be used together with run to restart the application as soon as we make changes to any file quite useful if you don't want to stop and start the project by yourself every single time you make any changes with dotnet new - age we see all the available templates there are a lot for instance the plain old console application and further down we finally got the Web API so let's use it we type dotnet new Web API and hit return now we see some files that have been generated for us in the Explorer let's go through them real quick at the bottom we see the weather forecast class 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 in the meantime we get a little pop-up telling us that we should add some files of course we want to add them you should see now that we got the dot vias code folder with the launch JSON and the tasks JSON file both our configuration files used for debugging source code format as bunless and so on but not very interesting for us at this moment so let's have a look at the startup class here we find the configure services and the configure method the configure services configures the apps services so a reusable component that provides app functionality we will register services in the future in this method so they can be consumed in our web service via dependency injection for instance please don't mind all these buzzwords right now the configure method creates the apps request processing pipeline meaning the method is used to specify how the app responds to HTTP requests as you can see we are using HTTP redirection routing and so on with all these use extension methods we are adding middleware components to the request pipeline for instance use HTTP redirection adds middleware for redirecting HTTP requests to HTTPS to make things a bit easier for us in the beginning let's remove the use HTTP redirection line or at least commented out the startup class is specified when the apps host is built you see that in the program class in the create host builder method here the startup class is specified by calling the use startup method in the CS project file we see the SDK the target framework in our case dotnet core 3.1 and the root namespace later on we will find additional packages like entity framework or in this file regarding the app settings JSON files we only need to know that we can add and modify some configurations here more interesting right now is the launch settings JSON where the current environment is configured and also the application URL with this URL we will find our running web service as you can see it'll be HTTP localhost 5000 the object and bin folders can be ignored for now we find temporary object and final binary files here very interesting and often used throughout this course is the controllers folder the first controller you see here is the generated weather forecast demo controller we get to the details of controllers later for now it's only important to know that we can already call the gets method here in the terminal we enter dotnet run you see here's already the URL we've seen in the launch settings Jason so let's open Chrome and go to HTTP localhost 5000 well the result of this URL doesn't look very nice that's because we have to access the weather forecast controller so when we go back to visual studio code we see the name of the controller it's weather forecast without the controller string we also see the routing huge Route controller to define how to access this controller will discuss how routes work in a future lecture so we just copy the name weather forecast go back to Chrome and enter the correct route and finally we get the results we can also see the results in the console you now let's do this with postman because postman will be the tool we will use to test our rest calls of the Web API if you haven't already make yourself a bit familiar with postman the essential part is in the middle we can choose the HTTP request method in this particular case it is get and then enter the URL and hit Send the styling of the result should to the console great so this works now let's move on and build our own web service there is one little thing we may do before we start with the Web API let's create a git repository for our projects on the left pane we go to source control and hit the plus button to initialize a repository we pick the dotnet RPG workspace folder and all our files are added to the repository the thing is that this is simply a bit too much stuff we don't want to commit the bin and object folders for instance so we need a git ignore file to ignore certain files and folders there are Visual Studio code extensions to help us out it's up to you which one you choose just look for git ignore and you get some suggestions like this one here called git ignore templates after installing this extension you can press f1 type generate and get ignore and then choose Visual Studio the template was successfully generators we can have a look at the gate ignore file and you see on the left that the number of files that will be included to this repository has been decreased that's exactly what we want now we simply add our first commit message like initial commits commit all changes and we're done 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 so far you learned how to create a Web API project in dotnet core from scratch and how to make your first API call with postman in the upcoming lectures we will create a new controller and models for our RPG protein game characters additionally we will turn our synchronous calls into asynchronous calls make use of data transfer objects and change the structure of our web api so that it needs best practices but first let's have a look at the Model View controller or MVC design pattern which is the foundation of all this Model View controller or short MVC is a software design pattern which divides the related program logic into three interconnected elements let me explain what every single one of these three elements stand for and how they collaborate we start with the model you could also say the data a character and our role-playing game is a model for instance it can have an ID a name hitpoints 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 read of you 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 you accept the results of our calls and postmen 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 is able to manipulate the data hence properties of the RPG character with buttons text fields and so on in a browser game date might be JavaScript code in essence maybe with the help of frameworks like angular react of UJS this javascript code in turn uses the controller to actually 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 over again well that sums up the MVC pattern now we're 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 first we create a models folder 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 shop class with a right-click otherwise you just create a new file so right-click the models folder then click new c-sharp class and call this class character now let's add some properties so let's add an ID which is an integer then a name which is a string and may be called the character Frodo by default then we can add hit points which is an integer strength defense and maybe also intelligence okay we will also add an RPG class property that means the type of the character but first we have to create a new enum for that so let's add a new c-cup class called RPG class and then replace class with enum feel free to add any kind of role-playing class you want to add here in this example I use Knights mage and cleric the most basic characters you would need I guess some melee actions are magic and of course never forget the healer now when we have the RPG class enum ready we can finally add it to the character model I set the default to the Knights but again that's totally up to you all right the first models are ready let's add a new controller now and make a get call to receive our first role-playing game character to add a new controller we create a new C shop class in the controller's folder let's call this class character controller before we can start actually implementing analogic we have to make this thing a proper controller to do that we first arrived from controller base this is a base class for an MVC controller without the you support since you'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 but in our case you just make sure to add controller base after that we have to add some attributes the first one is the API controller attribute this attribute indicates that a type and also all derived types is used to serve HTTP API responses 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 when we actually make use of these features regarding attribute routing that's already the next thing we have to add below the API controller attribute we add the route attribute that's how we are able to find this specific controller when we want to make a web service call the string we add to the route attribute is controller in brackets this means that this controller can be accessed by its name in our case character so that part of the name of the C shop class that comes before controller don't forget to also at the using directive Microsoft asp net Korn MVC on top of the file alright let's get into the body of our c-sharp class the first thing I'd like to add is a static mark character that we can return to the clients for that you also have to add the dotnet RPG models using directive so private static character for instance tonight and this is a new character and we add the using directive next we finally implement the get method to receive our game character so public the return type is I action results and get and in the body we just return ok and then the night so we return an I action result because this enables us to send specific HTTP status codes back to the client together with the actual data that was requested in this method with ok night we send the status code 200 ok and our mock character back other options would be a bed request 400 status code or a 404 not found if a requested character was not found all right the code is implemented now let's test this with postman it's pretty straightforward and the HTTP method is get again the URL is HTTP localhost 5,000 slash character and nothing else has to be configured hit Send and there is our night now pay attention to the attribute that was added to our get method exactly there is none when we compare this to the weather forecast controller we could have added an HTTP GET attribute but it's not necessary in the character controller because the Web API supports naming conventions and if the name of the method starts with get the API assumes that the used HTTP method is also gets apart from that we only have one get method in our controller so far so the web service knows exactly what method is requested however in the next lecture we'll have a deeper look at these attributes before we start with a new method let's add another mock character to the controller by replacing the singer character with a list of characters because we will implement an additional method to return dead lists so we remove the character and then we create a private static list of type character which is called carrot and this is a new list of characters the first one is simply a new character and the second one is so a new character but maybe we call him Sam don't forget to also add the using directive to system collections generic for the list type after that we have to make a slight modification to our existing get method we now return the complete list of characters let's test this modification in postman same HTTP method same URL hit send and there are our mighty Knights beautiful now let's add a method to return a single character and let's just return the first character of the list by default so public I action result get single for instance and then return okay characters and the first one when we try another request in postman now we're getting an error to be more exact we've got an ambiguous match exception this means the web api doesn't know which method to use because we have two gets methods with no parameters that's where we have to add routing attributes so let's add one to the first method and call the route get all you see with routes and then a string we can decide how to get to a particular method it's time to try this out in postman again when we use the same URL as before meaning a local house 4000 forward slash character we get the first character back when we now add the string get all after the name of the controller and slash we get all our nights back perfect there's still one more thing we can add and that's the HTTP request method in fact we can combine the route with the HTTP method it's quite simple just replace route with HTTP GET leave the string and you're done when we test this again in postman everything should work as expected now since receiving the first RPG character of a list can get quite boring let's add an argument to our requests 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 the default value is zero so we just add the ID with the value 1 to the second character now it's getting interesting we add a new parameter to the get single method and use link to find the RPG character with the given ID in the list of all characters we do that with first or default followed by a lambda expression this method now returns the first character where the ID of the character equals the given ID to make this work we also have to add the system link type the last thing would be to add an attribute with the route the HTTP request method and the parameter the parameter has to be added in curly braces that's it the parameter in the route has to match the parameter name in the function itself let's test that with postman the only thing we have to enter after the controller name is the ID for example one and there is Sam testing this with zero here's Frodo this works just fine 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 web Docs 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 deletes maybe also option and patch 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 characteristics to the service like an ID or 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 role-playing game characters sending objects to the service in turn would be done with their post requests 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 backend usually this new object will be saved 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 objects 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 deletes 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 clients you could in fact write a service method that uses gets but then simply delete an object with a given ID it's all up to you now how do the cruds create read update 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 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 clients in our case postman 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 public action result add character and as a parameter we use the character type in the body of the function we simply add the new character to the characters list and then we return the complete list so that we can see that the new character is part of the list last but not least we add an attribute to this method and that would be the HDD post attribute because we are able to send data to the service it's important to mention data or the JSON object respectively is sent the other body of the requests when we sent the ID to the service we did it via the URL now it's done with the body that's a crucial difference let's test that now you can open a new tab in postman choose post as HTTP method this time the URL is again HTTP localhost 5,000 and then character but now we also add a body to the call choose raw and also the JSON format it's okay to send a new RPG character with just an ID and a name to the service for instance three as the ID and the name maybe Perceval after hitting cent we see our complete list with the new character just keep in mind we don't store the data persistently so when we add another character we get four in total but as soon as we stop the webservice and started again the list consists of the two initial mock characters and the Edit characters are gone currently we are 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 into 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 that's where services come in the controller should actually be pretty simple and just forward data to the service and return the results to the client nothing else to be able to do that 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 will 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 getting an RPG character out of 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 DT OS we already have models but it's common to use these details for the communication between client and server the difference is this DT o--'s are objects you won't find in the database that means they won't be mapped models intern our 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 there's information the user does not need to see in this case we want to save this information in the database but don't want to send it back to the clients here 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 details 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 will use D TOS 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 and in there we create the character service folder in that folder we create the interface I character service and the corresponding implementation class character service you the interface gets three it's in essence the methods you already know from the character controller we have a list character get all characters then character get character by ID with an ID as an integer then list a character add character with the new character s character after adding these methods we have to add using directives for the missing types lists and character instead of adding them manually we can click the lightbulb or press control and period and select the proper using directive there as soon as the using directives already we can add the I character service interface to the character service class you should see an arrow now that says that the interface methods are not implemented again we can fix that real quick by clicking the yellow light bulb or pressing ctrl + period on the keyboard and choose implement interface this whole thing is called quick fix by the way as you can see the methods have been generated for us but we still have to implement the bodies and add the using directives again regarding the bodies of the new three methods we can actually just jump between the character controller and character service and copy and paste the code so for the add character method for instance we paste the code characters add new character and return the characters list regarding and get all characters we just returned the characters list and get character by ID we return the characters and then first or default with the given ID additionally we have to add the characters list to the class of course so let's copy this one as well last at least we add the system link type so that we can use the first or default method regarding the character Conte to implement some more changes first we need a constructor we can add it with the snippet ctor and we call this thing character service we then add the using director for dotnet RPG services character service and then create a new private field for the character service we can do that by putting the cursor over the argument it control period and then choose initialize field from parameter additionally I like to add an underscore in front of the field name so now we already inject our new character service into the controller the list of characters can be removed regarding the bodies of the methods we have to call the new private feared character service so the code inside the brackets of the okay statement has to be replaced by the corresponding character service method we start with the get method for instance so it's now character service get all characters then character service get character by ID for the get singer method and the last one character service add character new character alright let's test the first method in postman this means we choose the URL HTTP localhost 5,000 character get all as you can see we're getting in error it's a system invalid operation exception we are unable to resolve the service for the type I character service so the Web API wants to inject the I character service but it doesn't know which implementation class it should use so we better tell it to do that we open those startup CS and in the configure services method we add the line services ad scoped and then I character service and then the implementation class character service you now the web api knows that it has to use the character service class whenever controller wants to inject the I character service the beauty of that is that whenever we want to change that and use another implementation class for instance we just change this line and we are done you don't have to change anything in the controller's injecting the I character service with add scoped we create a new instance of the requested service for every request that comes in there are also the methods add transient and add singleton add transient provides a new instance to every controller and to every service even within the same request and add singleton creates only one instance that is used for every request we only need add scoped when we test all the calls again in postman we don't get an error anymore the get call for example returns Frodo and Sam as expected what are a synchronous 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 threat waits for this task to be finished and wouldn't do anything else until the task is done with an asynchronous call this threat wouldn't wait at all instead it would be open for new tasks and as soon as the other tasks for example 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 large applications with lots of users it can really happen that all threats 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 that's why it doesn't hurt to know this and also implemented early in this projects although the methods in the character service 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 so we add tasks and then in the brackets we add the actual return type like list character and so on you of course we also add the using director for system threading tasks that we switch to the character service class and also add the task return type and the using directives you additionally we add the word async to the methods you now we've got asynchronous methods don't mind the warnings for now the code will still be executed synchronously but when we add entity framework with database queries later on we'll have asynchronous calls but at least is the character controller again we add the task type with the corresponding using directive and the async keyword to every method you additionally we add the keyword awaits to the actual service call that's how we call an asynchronous method that's it making test calls with postman 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 and 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 these 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 create a new class and call the file service response the actual class name would be service response and then T in brackets where T is the actual type of the data we want to send back then we can add some properties 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 example 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 let's start with the interface we simply add the service response class here so we get tasks and then service response and then list character or tasks service response character and so on you after that we do exactly the same in the character service class you of course we also have to make changes to the actual implementations of the methods in general we create a new service response object in every method and set the data property accordingly so in the add character method we have a service response of type list character and we set the service response data to the characters and returned the service response and get our characters we again have a service response of list character set the data to the characters and return it you and in the get character ID method we have a service responsive type character and set the data to the character with the given ID you the character controller stays exactly the same no change is necessary here when we test the calls with postman now the results look a bit different for example here's the result of getting all RPG characters our characters are wrapped in our service response the front end could react to the new properties and provide a smooth user experience with toasters or something similar instead of presenting complex exception messages in the console or worse of frozen application in case of an error you already read about them now it's time to use DT OS first things first let's create a folder called DT OS and then another folder called character for all the data transfer objects regarding the RPG characters as already mentioned year behind details 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 will add properties like the creators and modified date or flag for the soft deletion of the character 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 clients 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 for 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 regarding the gate character look exactly the same as the character model for now I know it doesn't seem to make sense but I don't want you to be overwhelmed by implementing anything entity framework related at the same time adding the DT OS is a good preparation so actually we can copy and paste all the properties you the add character DTO looks a bit different let's say we want to send every property but the ID to the service so we can copy the properties of the model again but remove the ID now that we have our details ready we can use them in our controller and service methods we start with the I character service interface instead of the character type we now return get character DTO the parameter of the add character method now is of type add character detail we also have to add the corresponding using directive the same changes have to be made in the character service so we replace the character type with get character DTO and add character DTO respectively you as you can see visual to decode is not happy with that change the types do not really match and that's where we have to map the details with the model it's time for ultra mapper but Before we jump to automata we also have to fix one small thing in the character controller we change the parameter type of the add character method to add character DTO 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 automata is that it's doing exactly that for us on the fly but first we have to install automap of course to install we go to the terminal and enter dot net add package and then automata dot extensions dot Microsoft dot dependency injection without any specific version to install the latest package when the installation is done you will see a new entry in our project file after the installation we jumped to the startup CS first and the configure services method we register automata with services add automata type of startup and add the using directive ultra mapper to be able to use the mapping of automobile we now need an instance of the mapper in our service so in the character service we add a constructor and inject a mapper again we can initialize a feed from that parameter and add an underscore to the private fields you you now we can use the mapper to set the correct types to the data property of our service response let's start with the gate character by ID method using the map function we first decide in angle brackets which type the value should be mapped to and the parameter is the actual object that will be mapped the changes for the other two methods are pretty straightforward in the add character method we first met the new character into the character type because it will be added to the characters list so it's the other way around to map the whole characters list in one line and give it to the service response we use the Select method of link followed by a lambda expression where we map every character object of the list into a get character DTO you and finally in the get all characters method we map every single RPG character of the characters list with select again similar to the add character methods alright let's test this now with postman let's try it with the get all routes HTTP localhost 4000 character get all so as soon as our web api is running run the call in postman and we're getting an error we get an automatic mapping exception missing type map configuration or unsupported mapping so automap adult know how to map character in to get character DTO you might ask yourself it's called Auto mapper so why isn't this working automatically well we have to configure one more thing but then I promise ultra mapa 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 at root level we can create a new C sharp class and call it automatic profile this class derives from profile make sure to add the ultimate by using directive regarding the implementation we need a constructor with no parameter and then create a map for the necessary mapping you and of course add further using directives alright let's run our tests in postman again now everything works as expected the same for returning a single RPG character but what about adding a new character we have to create another map let's do that this time we map the add character dto to character when we test this now you see that everything works but the idea is zero that's because the add character dto does not provide an ID that's exactly what we wanted still let's fix this by generating a proper ID ourselves in the add character method in the character service we first create our new character based on the DTO and then set the correct ID by finding the current max value and the characters list and increasing it by one you you now without even sending an IDE Percival gets the correct one later when we use entity framework or it will generate the proper ID by itself all right we are 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 service interface the character service class and the character controller let's start with the interface and add the method update character the return type is a get character DTO so that we can see the changes directly and the parameter is a new DTO update character detail you let's add the new DTO real quick we create the new c-sharp last update character DT oh and actually can copy and paste all properties from the get character DT Oh you now we can implement the method in the character service we implement the interface automatically and then start with a service response you then we try to find the art character with the given ID of the updated character in the characters list after that we overwrite almost every property of this RPG character one by one this means the name the class defense hitpoints you intelligence you and the strength and finally we met the character do and return the service response you one last thing is missing we have to add the async keyword okay off to the character trolla in essence we can copy the add character method change the name the service method and the parameter and also the HTTP method attribute which is HTTP put you it's time to test that in postman first let's get all RPG characters in one tab for reference in another tab we can do the update call the HTTP method is put the URL is HTTP localhost 5,000 character and in the body we have to enter an ID and then the properties we want to change maybe give the character a different name more hitpoints and also turn the character into a mage [Music] it sends and there's the updated character 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 and leave the RPG class Perceval would be a knight again 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 even though they did not change alright that was just a side note now what about the whole character list this works perfect now let's try to update a character that doesn't exist just change the ID to two and see what happens we're getting a new reference exception 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 let's start with a try-catch block you in the catch block we just set service response success to false and the service response message to the actual exception message that's it already let's test that again in postman success is false and the message object reference not set to an instance of an object a possible front-end can work with that but maybe another message would be more suitable for the user alternatively we can add a slight modification to the character controller you see that we're still getting a status code 200 ok well a character wasn't found so maybe we can also return a 404 not found response so in the character controller we first get the service response then we check if the data is null if so we return not found else we return okay as usual you when we test that now in postman you're still getting the whole response back but the status code is 404 not found 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 to delete an RPG character again we have to make modifications to the AI character service interface the character service and the character controller let's call the method in the interface the lead character with ID as an argument and let's return the remaining RPG characters regarding the characters service we can implement the interface automatically again and then copy the code of the update character method and just make some changes you first we add the async keyword then we fix the service response because we return a list of characters instead of first or default we could use first the difference is that first or default will return null if no matching entity was found and first throws an exception so let's take advantage of that if however a character was found we remove it from the list with characters remove character in the end we return a mapped list of the remaining characters similar to the expression in the gate all characters or add characters methods nation of the get single and update character method you can copy the get single methods first change the method name to delete and also use the attribute HTTP deletes the body is almost the same as the body of the update character method only the service response is different and the call to the character service it is delete character with the given ID of course you let's test that the HTTP request method is delete the URL is HTTP localhost 5,000 character and then one to remove the character with ID 1 perfect this works just fine our Web API with all crud operations is done it's time to save the data in a database with entity framework or and sequel server now if you made it this far you are definitely ready for the complete dotnet core jumpstart course you seem to have what it takes to build a dotnet core application with Web API and entity framework or completely by yourself from start to finish in the next sections of this course you will dive deep into entity framework core with code first migration sequel server and all kinds of relationships meaning one-to-one one-to-many and many-to-many relationships additionally you will learn how to implement authentication into your application with the help of JSON web tokens this means users will be able to register login and create their very own RPG characters and after that you will do more than just crud by letting the RPG characters fight against each other even in a deathmatch as a thank you and reward for completing this part of the course I want to give you a pretty sweet discount make sure to use the link in the video description below I'm looking forward to seeing you again in the complete course [Music] [Music]
Info
Channel: Patrick God
Views: 49,219
Rating: undefined out of 5
Keywords: .net core, dotnet core, .net core 3.1, dotnet core 3.1, web api, entity framework core, .net core tutorial, .net core web api, .net core web application, .net core 3, .net core 3.1 tutorial, c#, .net core c#, dotnet core 3, dotnet core application, .net core application, entity framework
Id: H4qg9HJX_SE
Channel Id: undefined
Length: 75min 58sec (4558 seconds)
Published: Wed May 20 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.