.NET 7 Web API & Entity Framework 🚀 Full Course (CRUD, Repository Pattern, DI, SQL Server & more)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
dotnet 7 is finally here so now is the time to build a web API with all the crowd operations meaning create read update and delete using the HTTP request methods get postput and delete and we will start with the fat controller but bear with me here directly after that we will make use of the repository pattern meaning we will create a service inject the service with dependency injection and after that we will also utilize entity Frameworks heaven now to store your data persistently in a database let's start alright real quick here you can see it you can download.net7 now and let me go to all.net7 downloads here you also see all the options and really important you need Visual Studio 2022 version 17.4 for that it took them a couple more hours after the release of the.net 7 SDK to also release version 17.4 and they only had the preview Edition when they released.net7 but now it is here and if you want to use Visual Studio code it works either way alright so just make sure if you want to use Visual Studio 2022 2022 that you have versions version version 17.4 Jesus it's late sorry about that so we will use Visual Studio 2022 the Community Edition here got lots and lots of tests already here but let's now create a new project and we want to build an asp.core web API you see the core term it will never leave I guess and also here not only in the recent project templates you can also see it here of course asp.core web API with c-sharp please and that's what we're going to do and we call this well I love I still love superheroes if you are subscribed to my channel you know that so let's call the superhero API and now with.net7 we hit next and there is.net7 standard term support meaning the support 4.7 is only 18 months 4.6 it is three years so the support will run out 4.7 before it runs out for dotnet6 but I guess until it's that late we will already have.net 8. so now I think it's it's okay to use.net7 and it it gets uh lots and lots of great new features not only regarding uh the web API and ef7 also Blazer but more about that in later videos so now authentication type won't use anything here configure for https is great we use controllers the old school way to build apis not the minimal API and we enable open API support so that we get a cute speaker page where we can test our API but more about that throughout this tutorial so let's create this now and this thing already exists so let's go back real quick and let's just add um API dot Net 7 here all right great name now let's create this thing and in a couple of seconds we should see this and I will start explaining some stuff for the absolute beginner or for the beginner of web apis with.net here you see the project now well on the solution with the new project here we've got a bunch of folders properties and the controllers folder app settings the program CS file and the weather forecast model so let's go through that really really quick regarding the launch settings what we see here is actually when we run the application it will be available under a certain application URL as you can see here and here so for instance let's just do this real quick we start without debugging if you use this button we would we would be able to use debugging but with this button here it's it's a bit faster I like it that way because I not one I don't want to use debugging all the time when I'm starting my apps and here we are this is already Swagger and we can already see interesting stuff here actually we see the schemas or you could also say these are the models so the weather forecast model using the date only type here not new with.net 7 but still kinda new and here you can also see these types day of the week this is an enum and also the day date only where the day of the week is used and again the weather forecast then uses the date only so this is already quite neat I guess when you use Swagger that you see the the models that are used here in this API and now the default example is the typical weather forecast it is a get method meaning we just well grab data from the web API here we can try this out we can execute this and then we get randomly generated whether forecasts isn't that nice and when we now have a look at the codes or wait a sec you see the URL this is what I also wanted to tell you seven two five six is the port for the https um well version let's say or application and here you can see this as well 7256 and the launch URL is Swagger so that's that then and in this case we get access to this uh well to this page here meaning Swagger with the API documentation all right that's that and now again in the weather forecast controller we let me just close the solution Explorer for a sec we see this method here already again this is for the beginner you can see the time codes down in the video description in the chapters below the video so if you already know that please feel free to skip the chapters so this is the HTTP get method we already see this attribute here HTTP gets the name is not that important here really all right just important is the HTTP get this attribute well says it here identifies an action that supports the HTTP get method and in here now we see the return type I enumerable with the weather forecast model we can go there of course as well and here again we see the date only type the temperature in Celsius Fahrenheit and the summary which is another string and here again you see that it simply returns randomly generated temperatures and summaries and the summaries come from yeah come from here could be freezing bracing chili and so on so this is everything that's going on here we already see a little bit of dependency injection meaning the eye logger is injected here but maybe for the beginning this is a bit too much we will build our own web API and where we also use the different HTTP request methods get post put and delete we will also use um dependency injection then when we use the repository pattern and also later when we use the Entity framework and we will of course also build the default controller let's say that is inheriting from controller base and what's that as you can see here a base class for an MVC model view controller controller without View support if you would need View support we could use this class actually but controller base is just fine for us this is not an MVC application this is just the web API and this stuff is really great because I'm trying to access this class now it should work control and left Mouse button to get there you get lots and lots of stuff with that class for example the HTTP context the HTTP request the response and a later also interesting when we find it here the claims principle there it is line 216. so this is for instance a important or useful when you're using authorization authentication with that then do you get the user object that is in the HTTP context as you can see here as well and also you get lots and lots of different result options object results with a status code for instance let me just search for that again yeah there is already we can return an okay result this is what we already got from the weather forecast controller here meaning the status code 200 is returned as you can see here and this just means that everything went fine but we also get I don't know if they wrote it here yeah for instance the status 404 are not found everybody knows that even the people that don't write any code so for that you could return the not found function here all right or you could use this function to return a 4 4 status code so lots and lots of stuff you can also have a bad request forbidden and so on and so on like unauthorized wanted to say unauthorized here so this is the controller Base Class I think this is enough about that so let's go back to the weather forecast controller and the last thing I want to already tell you here are these two attributes let's have a quick look the API controller as it says it as it says here indicates that a type and all derived types are used to serve HTTP API responses so well we need that we want to use this stuff and this is why we need this controller here as well this attribute here and the route specifies an attribute route on a controller now this is how you well Define this endpoint in essence and how you get to this thing and in these brackets here meaning the term controller in the brackets is a convention which means you can access this thing by typing in weather forecast so the term that comes before the controller term and when we go back to Swagger you can also see it here we executed this and as you can see here the current statement Satan says it or also the request URL says it we've got our https localhost and so on and then only weather forecast all right and also important we use the get HTTP request method so this combination this URL with the get request method leads to this certain endpoint here and with that we get a bunch of randomly generated weather forecasts all right I hope this makes things a bit clearer already we um we can also have a look at the program CS this is the only thing that maybe is also interesting the app settings is really not interesting for now here since.net6 we we only have the program CS file earlier we also got a startup CS file where we got a configure method in the configure Services method but that's not the case anymore you see this is really really small and this well I think this is because of the new minimal apis right Microsoft wanted or the.net team wanted to well make it more usable make.net more usable more approachable let's say and easier for the Developers well when you use minimal apis this is just a side note it looks a bit more like node.js if you have some experience with that so maybe if you feel at home with Note then this is definitely something you want to have look into it you want to have a look into I've got some videos about that on my channel so maybe you can check out the info cards or just well maybe you wanna subscribe and then see all the other videos but here then the the whole Magic happens um we create the Builder here we add the controller Services we add the endpoints API Explorer configures API Explorer using input metadata and so on do not want to get into more details here we've got some middleware like use authorization use https redirection meaning redirect HTTP requests to https and so on and in the end we run the application one tiny little thing here add Swagger gen this is the um well the Swagger stuff and you also see it here in the tooltip that this wash Buckle asp.net course record or just the swashbuckle package here is use swashbuckle asp.net core funny little name but when you have a look at the project file here you can see this is the package that is used here all right so here now we will then configure our original just our services when we use the repository pattern together with Entity framework with the data context that we then need with Entity framework all right now let's take a deep breath I think this is enough for the beginning here now let's build our own web API and for that let's just close everything here and we go to the solution Explorer and we will create only one model and this will be the superhero maybe let's create a folder for that and call this models and in here now we create a new colossal at class and we call this super hero all right there it is and in here now we just add some properties with prop and then tap twice we can add this property here first thing I want to add is the ID the next thing is a string which is the name of the hero and you see this little warning here not another property name must contain another value and so on so I would say by default this is simply an empty string or we could also make this simply a nullable string and now let's also copy this and additionally to the name I want to add the first name the last name and then also a place that this would be the first name the last name and then also a place all right so this will be our superhero class and now we can already build a controller so right click add and now we choose controller not a class not a new item we can already go to controller here and then we get again some options it's not an MBC controller it's an API controller and here we also see some options an empty controller an API controller with actions using Entity Framework read write endpoints using Entity framework creates crud endpoints given a model class and database context using energy framework so you can already and you see it here minimal API scare folder you can already create controllers with a generated code but for me not only it's not only the best way to learn in my opinion to use the empty one even later I tend to use the empty ones because I want to write the code a bit differently Maybe but still this is totally up to you I guess for this tutorial for this little course here it makes sense to choose an empty API controller all right and then we will add the crud operations one by one so let's add this thing and we call this now Super Hero controller simple as that and as you can see here this empty controller now also has the controller Base Class inherited we got the API controller attribute and also the route attribute here they added by default the API string here so API forward slash and then controller when we have a look at the weather forecast controller again you see that the API string is missing it's totally up to you how you want to use it I like it that way actually so this is absolutely okay all right so now let's create our first method already and this would be an HTTP get call so HTTP get is suggested by intellicode and this is totally right and now we say public async task we return now an i action result all right as you can see here defines a contract that represents the result of an action method meaning with that we want to return status codes okay not found whatever it is and we can call this get all heroes for instance all right so we return a complete list of uh Heroes and in here now let's just create um a list of superheroes so VAR Super Heroes is a new list of a super hero and in here now we just use the object initializer to create a new superhero and yeah I do one is great then the name my favorite one is called super is actually called Spider-Man and do you know the correct name a first name is Peter then the last name would be Parker then and the place this guy lives as far as I know in New York City and now I'm curious does formatting work I did not work with uh version 17.4 of Visual Studio you can double check help about Microsoft Visual Studio 17.4.0 and the formatting does not work here so we do this manually again and again and again this is our superhero now and what we do is simply return in this case then not see this is not the superheroes we return okay and then superheroes and with that as you can see here creates an okay object result that produces in status codes that is 200 okay response so this is really what we want to do here all right one more thing about the attribute here when you want to use suveger you need this attribute if we would not use it or add it here it would still work but zweger would not work alright so if you want to use Swagger here then you have to specify the attribute there is a convention in a web API so every function that starts with get for instance then assumes that this is actually a get method so if you want to use Swagger please add the attribute otherwise it would not work now the little warning here just States as you can see these async method lacks await operators I know that but we will add a weight or a synchronous calls later when we add Entity framework so bear with me here please for now let's just run this and as you can see in a second when subweger opens yeah there it is fetch error filter.api definition and now let's just add the attribute again and well this was really really quick hard reload edits best really enable browser link enable CSS hot reload and hear hot reload on file save make sure that this is activated hard reload on file save because with that then the application will reload in uh in the back so now we've got our superhero call here right but what you can see in the schemas or in the models there is no superhero type so why is that and also here we see no suggestion here we actually see something is going on we what we expect here an example value well that's because of the I action result we can change that of course not using the interface we can actually Define the type that we expect here and in our case that would be a list of superheroes so one more angle bracket save this again and maybe save this again and it doesn't work so maybe we have to restart the application and now it works all right so still sometimes a little bit buggy but as you can see from time to time just restart the application and maybe the errors are gone and now we see our superhero type here with the ID the name and so on and now here we also see a suggested example value or example value not a suggested value an example value and now we can just try this thing out we can hit execute and we get Spider-Man isn't that nice so that's it already this is our first get call and now let's just move on with the other crud operations maybe the first one here is uh well it's maybe the fifth collaboration where we just want to get a single superhero so maybe we can move this up here and make this uh private static list of Super Heroes all right and now here we just return our super this is everything that we need actually all right and now let's copy this and return a single hero so get single hero maybe and for that we need an ID right so let's add the parameter ID and where do we get this ID from well we can change the route that of the endpoint actually so again we can use the route attribute here and that will look like that we add the brackets here route and then in parenthesis we Define our route and since we only want to use a parameter here we add curly braces and write ID so this thing then has to match with this parameter here but we can combine the HTTP method with the route attribute so let's just copy whatever it is in the parenthesis and remove this attribute and this works as well all right and now here let's just say we want to have a specific hero of the superheroes and let's just find where the ID of the superhero equals the given ID and in the end we return a hero here all right so let's just add a second one with id2 we call this guy now Iron Man and this would be then Tony Stark and as far as I know this guy lifts and Malibu correct me if I'm wrong and again let's just try that just saved everything we already have our second get method here you see the ID here as a parameter so let's try this out we choose one hit execute and it says object reference not set to an instance of an object this is interesting maybe we can just restart our app again try this one more time and now we get Spider-Man alright so just ignore this little error here let's try it with two we can execute there's Iron Man what about three now 204 undocumented okay this is a bit strange maybe we can change that so maybe now we can actually make use of the not found the 404 status code so maybe here we can check if hero is null then return not found and we add a little message like sorry but this hero doesn't it exists all right let's save that and maybe we don't have to restart our app now we hit three sorry but this hero doesn't exist and we get a 404 back and by the way if you want to use the console here with the developer tools you can do that as well of course let's filter for fetch xhr which stands for XML HTTP requests and let's just execute this one more time and here you actually see the same result right this is the request URL https and so on API superhero three it's a get method status code is 404 and in the preview we see this message here right and let's just try it again with Spider-Man execute we see this call here it's a get method status code is 200 and the preview then is exactly the same stuff we see here in Swagger isn't that nice all right so get all heroes Works get a single hero works and now I would say let's add a hero so again we can just copy this and here now this will be HTTP post for adding a hero let's call this Edge hero maybe and now we need a type here and this would then be this superhero type with an actual hero we do not have to search a hero this time we just say superheroes almost super heroes and hero that's exactly correct and in here now we return our superheroes alright that's already it so just make sure to use the HTTP post request method and in here now we use this type if you want to be absolutely sure you can use this attribute here from body specifies that the parameter probably should be bound using the request body so in that case you make sure you are expecting this object here in the body but since this is a complex type it will be expected in the body anyways and we will of course send it through the body we will not add a parameter here in the URL actually like it's done here you can do this in the put method when you want to update a hero but we'll get to that in a second so now let's just add one with HTTP post and this add hero method and yeah we also return a list of superheroes and with that I actually see that this is totally wrong we are not returning a list of superheroes you see it still worked so this is nice you see it doesn't really have to uh to be correct the type you can still return whatever you want to but uh I think it's it's better to see it or to well just do it correctly because then Swagger will also uh expect this uh the the correct type here as you can see we still see the list here with the bracket but now when we save this this should be gone and maybe we have to restart the app again and now we should only see this thing here again double check list oh my gosh reset the application again the single one now it expects a list all right so this is what I actually wanted to show you and I'm glad it worked although we have to reset the app manually a couple of times okay now let's add a superhero maybe we can just get one first so you don't have to type everything although Swagger is helping us so let's just open this for the update it makes sense to just copy and paste the the complete object but here now as you can see this is our request body we add ID3 we say this is Bruce uh Bruce Wayne yeah Bruce Wayne let's start with the first name Bruce Wayne lives in a Gotham City and who is it of course this is bad bad man it's late sorry about that all right so ID3 names Batman Bruce Wayne Gotham City we hit execute and now we get three superheroes isn't that nice so this is the update this already works again the request URL the type is now post and well again we get them back so this works just fine sad thing now is it's really unfortunate when we now restart the the web API we will lose Batman and this is why we need Entity framework later on but as you can see here now when we get all the heroes we got Batman as well and again if we restart this thing now and again try this out we only get Spider-Man and Ironman back because of this list here right okay so this is the post method now let me copy this get method here again no let's all right yeah let's let's just use this thing you see I really don't have a script or anything.net7 and visual studio 2022 version 17.4 has just been released have just been released so um yeah I just want to create this video as fast as possible so you see the current version of dot net and visual studio 2022 so now let's use the put method to update a hero and I already told you you can use this within with a parameter here or you just say you want to use this object and grab the ID from this object then so again let me just copy this here we return a list of superheroes we call this update hero and in here now we get a super hero for instance but if you want to use the parameter we can do this as well then we would need the ID here as well so we've got HTTP puts again you could you could just remove this and this I hope this this is clear then and then we will use not uh this ID we would then actually use hero ID and maybe you can call this request and it makes more sense so request and then a request ID so we just grab the ID from the given hero from the client or again we just use the URL like that all right so with that we also get a hero and again let's just call this request so uh we do not get into trouble here with this variable so let's do like that for instance and um you want to find the specific hero if we do not find it that's pretty sad but otherwise we just manually update the properties right so now we can say hero um yeah first names request first name hero last name is the request last name and the hero name is this and then we get also the place where is it there it is all right and in the end we well we could return only the one hero but I already changed the type so the return type so again we return all our superheroes so let's try this edit where is the problem I don't see a problem here let's just save everything again and restart the application we've got build our errors uh okay show me the build errors where is it oh that's nice process cannot access the file because it's used by another okay so let's just stop this and try it one more time okay foreign methods so now again we get all our heroes this is nice this is Spider-Man and when I now try to change this we can try this out we now have to add the ID here because we're grabbing this ID right and now I can change the parameters here don't need the ID in this case if you would choose the other way then of course you need it and let me just say this is now Amazing Spider-Man and let's just leave it let's just leave it as at that and we execute this thing and you see we now get Amazing Spider-Man and here when we get all our heroes this is also the case right so this already worked and of course just here a side note when let me let me just refresh the page and then we say we wanna for instance update Tony Stark right and this guy now is uh now called string and we only want to change the name of this guy well the problem is our method here will update every single property except the ID of this superhero then right so if you would just leave it as bad then as you can see here the first name the last name and the place would also be string so we executed this oh my gosh Iron Man is actually gone he's now called string first name last name is also string and he lives in string that's pretty unfortunate right so you really have to pay attention when you're designing your API and maybe also your client do you want to update a single property and in that case you would have to change the methods maybe or um you you say you build a client that is first grabbing the current object the current state of the object and with all the properties you well you have stored in the database for instance and then even if you only change one thing you still have all the other properties correctly right so you kind of overwrite them but the value is still the same I hope you get what I mean so just pay attention here when you make an update you can well you can do lots of stuff that is maybe not really intended by you or by whoever designed the API or the application really right okay so that's that update works and the last method that you need is the delete method so let's copy this again and now we use HTTP delete again we need the parameter here call this the lead hero and then we remove the the hero parameter we use the ID again this can still be the same and the only thing that you want to do here is now superheroes remove hero and telecode is awesome so now Jesus again all right let's edit this what's wrong here task action result list superhero I think everything is okay let me just stop the app again kind of feels like this version of Visual Studio was a bit rushed Maybe because I saw in the chat of the.net conf that some people were asking where is the latest version of virtual Studio because you can only use.net 7 with the latest version of.net7 except you're using the preview Edition so maybe it's a little bit buggy here's our delete you try this out and let's remove Iron Man with id2 hit execute and Spider-Man is the only one that's left and double check here execute that's true all right and this is or these are all the crud operations here but now I promised you that we not only want to use fed controllers and what actually are fed controllers well it's exactly that what we're building here meaning that all the logic is in there in the controller and this is really not the best design what you can do here now is make use of dependency injection in the repository pattern meaning that you create so-called services repositories and these repositories then will be injected here by the controller in the Constructor and yeah then it looks a bit better because the controller then only four Watts the the request to the actual service and thanks to dependency injection we can change the service real quick but let's just build this stuff and by the way we will go way deeper into all that in the.net7 jumpstart course so maybe you want to have a look in the video description and learn a bit more stuff so with that little commercial out of the way let's create the service folder now and maybe stop the application from running so right click and here now we add a new folder and call this services and let's also create another folder in here called super hero service all right and in here now we add a new item and this would be an interface and this is then the I super hero service and [Music] additionally we add a new class and this is the super hero service all right and this thing inherits or implements the I superhero service okay one more important thing here is we have to register this stuff but maybe we can try this out first and then you will see why we have to register this so now first the interface what do we actually need it's pretty similar to the stuff you already did here we need functions like the ghetto here or get all heroes get signal hero and so on so let me just copy this and paste it here and maybe we can do this um we can Implement all methods at once and then then let's just have a look how this changes then in in Swagger and in the controller and so on now the first thing here as you can see well where's the superhero we are here in dotnet 7 right and since dotnet6 we've got or let's say we are here in C sharp 11 now and since C sharp 10 we've got the global namespace so back to the controller you can see that it's using the model's namespace and let me just remove this here and maybe we can go to the programs yes and here at our first using and and now let's just add a global here as well and with that now the controller knows yeah let's stop everything please the control announced the type and also our [Music] interface okay now I I get what I did here no no it's correct all right so in the interface we Define our methods right so we've got the get all heroes then we have to get a single hero only returning one superhero then we get add hero returning a list again of superheroes all right and then the updates again returning a list just remove the angle brackets here all right and then the last one is the delete method copy this paste it here that was Ctrl B maybe this happens to you also sometimes and return the angle brackets all right so now we've got our interface I thought the application was already stopped all right so get all heroes get single hero and hero update and delete and now in here we just use the Quick Fix menu with control period and say Implement interface and now we've got all our methods great and again it's some copy and paste action here we just well first we move these zeros here to the actual service all right and now we've got got lots and lots of errors here of course let's grab this code from the delete hero method paste it here now here we return all superheroes all right and in here now this is tricky because we cannot really return a status code here what we want to return is a list of superheroes so the only thing that we can actually return is well maybe now or an empty list but let's just return null here and create some well custom convention here and then in the controller we check if the result is null then we return a not found maybe or a bad request something like that all right another option for that and this is again something we do in the jumpstart courses that you create a wrapper object a service response that grabs the data together with a message maybe also a Boolean value that says that the request was successful or not I don't know maybe even a status code something like that so a wrapper object where you where you then set the the superhero list with some more information and with that then you wouldn't have a statement like this thing here return null and then you check for now you would have a Boolean value for instance or your own status code something like that and then the controller could work with that and return the proper type right the proper status code so this is something to think something to think about maybe but for this little course here and we're already 50 minutes in maybe we can do it like that so what you now want to do is we have to inject the superhero service for that we need a Constructor again we can use a built-in snippet here similar to prop we use ctor hit tab twice and now in here we say give me the I super hero service we call this superhero service and now here we create and assign the field superhero service what I like to do is add an underscore here and you can actually configure this in a visual studio but let's just do it like that now so that there's uh by default Visual Studio would add the underscore here but this is totally fine and now we can access the superhero service together with the methods right and now down here which is all the red lines here now we say the results is superhero service delete hero with the ID and that's correct and in the end we can return the result but let's say if result is now again we return not found and again something like hero not found all right so again this is our convention in Jesus Christ I am clicking now I don't want this application to run but somehow it is still running I don't know why and this is definitely a bug of this latest version of virtual Studio 2022 not nice really not nice but anyways this is now the delete method we as you can see here we access the superhero service and delete the hero we use the delete hero method right so again let's just Implement all the other methods as well oh my gosh okay so here again we copy this for the update and where is it oh I use it in the update hero nice okay did not see that why didn't you tell me and here is the delete that's the one and regarding the update again we can actually Channel and then update the properties is that yeah that's true okay for this tutorial I think that's all right and in the end we return the superheroes okay we can actually do it like that same here all right and now in the controller we copy this again paste it here and now we are calling update hero with the request and that should be it all right so you see you're really just forwarding the request in the actual logic then is in here and of course we also have to change that in the interface so let's say that should be I hope yeah okay Visual Studio is getting this now I'm really confused sometimes if I did something I don't know if I did something wrong but what is probably the case most of the time or Visual Studio is not getting anything here and I am I'm afraid to hit save because then it will tell me yeah there are build errors of course and the app is still running all right so we've got the update covered we've got the delete covered and now maybe we can move on to the add hero let me just copy this again and here now we are at the ad hero superheroes and hero return superhero so this is actually quite simple and again we copy this paste it here add hero this is now called hero we do not have a null check we just return the result all right this is still the asynchronous warning now the next one is actually get all heroes for instance or get single here we are I'd get single hero and here as well again we simply return null all right and return in this case the hero let's make this nullable here as well okay and now in the controller we copy this we should really refactor this get a single hero with a given ID all right that's that and now all heroes and then we are done so superhero controller simply returns all superheroes so here we turn Super Heroes all right and here now you can actually say oh my gosh return superhero service get all heroes save this restart the application problem is I don't know if this worked so you know what let me just restart visual studio and with that I hope we can be sure that we've got our new version here with the service so let's close this all right and now let's run this again that looks better all right so now let's see you want to get all the superheroes we try it out we hit execute and we get an error and this is what I wanted unable to resolve service for type I superhero service all right while well attempting to activate the superhero controller and this is why you have to register this stuff so back to the program CS now and in here now we say Builder services at scoped I super hero service superhero service and now as it says here it's a scoped service of the type specified in ICP or service with an implementation type specified in Superior Service to the specified isource collection so we registered the service here also got at Singleton it's a Singleton service and transient but most of the time a sculpt one makes sense so it's scoped and this really means whenever a controller a service whatever it is wants to inject the I superhero service the web API knows that it should use the superhero service implementation great thing about that is if you for whatever reason want to implement a superhero service two or three or four or whatever it is you wanna play around with all that stuff here and you do not want to change this code so you you really don't want to touch it and in this case you can just create another file superhero service 2 for instance that is also implementing the interface then the only change you have to do is in here you can then say I want to use superhero service 2 in this case instead of the first one and you do not have to touch the controller because it is injecting this interface it is using this interface isn't that nice so this is the magic of dependency injection so let's save this let's restart this manually I mean I had the same problems one year ago and I am well I'm a bit confused that they're still here they got even worse actually with the latest update so I hope they're they're fixing Visual Studio in the next days if you have similar experience please let me know in the comments so now try this out hit execute here how our heroes we can get a single one execute perfect we can of course add one with ID 0 Maybe there it is and we can change one with ID 0 this is now the name String one execute works and let's remove this one again ID 0 execute gone and up here it is also gone perfect so now this looks better we have the controller that is only forwarding the request okay we've got this little logic here bear with me but then we already use the magical repository pattern dependency injection with our I superhero service and the superhero service here isn't that nice all right and now the next step is to finally add Entity framework with SQL Server to store the stuff persistently so when you restart your web API the data is still here and actually again we're using the repository pattern and the unit of work a patent with Entity framework so now you already know how to inject a service and we will also inject this data context now that we are going to build next with the use of Entity framework but before we can actually use Entity framework we have to add some packages and also add the.net Entity framework framework tools so the very first thing again the dot net Entity framework tool so in here what you have to add maybe you already have it in my case of course it's already installed so with.net EF I can see I've Got The Entity framework core.net command line tools version 7.0.0 installed the current.net version here is 7.0.100 all right so now to to to get the the tools here you have to write the following line dotnet tool install dash dash global and then.net dash EF in my case it's telling me it's already installed but what I can do is I can either choose update like that reinstalled or I can actually uninstall it and then install it again and with DOT net EF I can double check yep now it's it's installed great the next step now is nuget packages so right click the project file manage nuget packages and then we go to browse make sure to choose the browse tab I do this mistake all the time search for something on the install Tab and I don't find it and I'm asking myself why the heck do I not find it so in here now we can actually add Entity framework and there it is Microsoft entry framework core and Jesus 500 million downloads that's a lot we see version 7.0.0 so let's install this thing please yep we accept everything next would be maybe it's already here yeah design also necessary for the code first migration that we're going to use here share the design time components for entity thermal core tools so install this and since we want to use SQL Server we also look for SQL Server there it is also version 7. install this thing and we are done with the packages and the tools and by the way if you do not have SQL Server yet we are using the free Express Express version so SQL Server Express is the correct name I just Googled for it in another window here there it is so you can Google for SQL Server Express and then just click here SQL Server Express and here you get the express version it's a free edition of SQL Server so you can download it here I already got it and additionally what you can also use is the SQL Server management Studio there it is and this is really a great tool that you can download it to have a look at your database change it modify data add some lines and so on but you will see all that in a minute so if you do not have SQL Server Express yet please download it and maybe you also want to download the management Studio you can also watch your database with Visual Studio but I really like the management studio all right okay so please do that and then come back to this video alright and with that we can add our data context so what I usually do I create a new folder new folder called this data and in here now we add a new class and we call this class and data on text all right and this thing now it's using the DB contacts and we need for that we need the Microsoft ND framework core namespace and let's just use the global keyword here as well if you want to be more organized move this to the program CS but this works as well all right and here now let's just read this together the DB context what is this a DB context instance represents a session with the database and can be used to query and save instances of your entities dbcontacts is a combination of the unit of work and repository patterns EF core does not support multiple parallel operations and so on but the most important thing here is it can be used to query and save instances of your entities and you can use Link to do that right so you just inject the data context then and with the help of this context you can access your data modify it remove it and so on and this is freaking amazing so let's use it but first we have to write some code so the first thing here is the Constructor so cdor again and now the data context gets a parameter which is DB context options of the data context call this options and we have to run the base Constructor here as well and another thing we need is a connection string so we can do this in different ways we can use the application as the app settings file here to add the connection string and then register this thing in the programs yes again this is a way we do it in the net jumpstart course but maybe here we can add another way that is also totally fine and that would be the on configuring method so overwrite and then on configuring that's the one we've got the options Builder here and with that we can say options Builder use SQL Server so with that now you have core knows that we want to use the SQL server or Entity framework seven it is called Entity framework seven now the chord term is used internally of course but the well Microsoft or the.net team divorce the old Entity framework actually and now the new DOT or the new Entity framework 7 is actually the well the latest entry permacore version that's just a side note and now here regarding this connection string this can get a bit complicated for you it might be different but if you have the same situation as me meaning Secret Service secret Server Express is installed locally on your machine then you need the following so server would then be periods backslash backslash SQL Express then the database this is up to you so the database name would be something like super well it's called yeah let's call this super hero no superhero DB like that that's great then trusted come on connection is true and now comes something new with.net 7 or entity frame X7 we also have to enter Trust server certificate and set this to true as well alright so here's the complete thing server is SQL Express the database is the superhero DB trusted connection set to true and then also trust server certificate also true all right and with that out of the way we add the database set in our case this would be the superheroes table so we can add another property here DB set a DB set can be used to query and save instances of T entity link queries against Libby said it will be translated into queries against the database meaning when we've got our superheroes database set here we can use the link to make energy framework create SQL statements in a sense to well do the same thing and then return the requested data for instance so the type here would be the superhero and now the name of this property is usually just the pluralized name of the actual model and this then is the the name of the table that we will uh we'll see then in the database in the end so this is now our superheroes property our DB set and this is everything we need here in the data context for our code first migration but we also have to register this thing in the program CS so we can save this and now in the program CS file here we add again Builder services and then add DB context and here we wanna actually add our data context yeah stop this and of course we add this uh using directive and make this Global maybe all right so we registered the DB context we also got it configured here and now the next step is to use.net ef the.net ef command you can see it here already.netf we've got three commands database DB context and migrations the first thing we need is actually migrations to add a new code first migration so net EF migrations add and since it's the this is the first one typical way to call this is initial create because this would also create the database and you have to make sure to be in the project directory here so CD for change directory and now do this one more time and we've got an error all right let's do that with Dot and builds five errors okay maybe we can see them here as well I need your frame a chord does not exist here and that's interesting let's have a quick look well actually it is here maybe we can rebuild the solution then have a look at the data context there it is let's try the.net build command one more time everything is okay all right build succeeded and we're done and now we get a new folder migrations and in here you see what is actually going on when we run this migration in the up method we create a table called superheroes with the ID the name first name and so on and already we set the primary key the ID will be the primary key and the down method we simply drop this table this looks great so now let's run this again we can use dot EDF but this time with a database and then update and don't be confused here when the database does not exist the update command will also create the database so we run this and we should see all the commands yep there they are so we create table superheroes for instance and so on and now we can actually start the SQL manager SQL management SQL Server management Studio there it is we connect we see some databases yeah play the e-commerce.net RPG and now also this Superhero Database with these tables EF migration's history some internal stuff for Entity framework but also our superheroes isn't that nice with these columns and right click edit top 200 rows and there are no Heroes of course because we have to add some so let's add Spiderman again Spider-Man Peter Parker New York City and then let's change our superhero service all right so back to visual studio and here's our superhero service and now let's say we start with get all heroes alright but first if you paid attention we need a Constructor to inject the data context again so ctor and here now we say data context context again we add this field at the underscore if you haven't configured Visual Studio correctly or properly but you don't need it you can use the this keyword it's totally up to you of course and in here now we say of Our Heroes is a weight text superheroes and then to list async all right and here now we say return Heroes perfect and since I'm using an asynchronous function here now we also have to change the return types so now we're actually returning task list a superhero and oh yeah okay this time that was that's correct okay so that's that and let's also change the interface so here we're returning task like that and actually well let's let's just keep it for this little test here and in the controller we have to call weight and now all the warnings what this warning in essence at least should be gone let's run this and then we'll see if we now get the heroes from the database all right okay I hope this is the the correct version try this out hit execute and we get Spider-Man that's correct and when you have a look here in our superhero service actually there are two Heroes and maybe here now we can add another one Batman again Bruce Wayne Gotham City and we just execute this one more time and now we get Batman isn't that great so no restart of the web API or anything we just get the data from the database this is nice this is really really nice so now let's change the other methods first let's change the interface and maybe again I'm just used to close the terminal and then the yeah now it stopped all right so of course must have been me I did something wrong I don't know what but something was not correct so now I wanna use asynchronous methods here and that should be it I hope we save this and we change it here as well so now here we return tasks and these are then async methods okay so here as well async task superhero and here async task list superhero and here as well all right okay so get all heroes and now let's Implement all the other ones we want to get weights contexts Superheroes find and now here we can simply use the ID find async method because it's using the primary key finds an entity with the given primary key values right so find async ID if the heroes null again we just return null that's that and here we do actually the same stuff so let's just copy this okay what's up with the cursor now funny and here is the request no not true still the ID great and let's see so here in the update this is important we can do it like that but then what we have to do is we have to save the changes right because with that we made a change to the object but we have to tell Entity framework that this should be actually written to the database and we do it like that we say wait contexts save context context save changes async all right so again we get the superhero from the database change the properties and then save changes async and this is what you have to do also when you add a hero to the database in essence to the database table and when you also remove one all right so we've got the get all covered get single is covered and update Heroes covered and now delete similar stuff yep our hero is this and here now it is context superheroes remove hero and then again we say weights context save changes async all right and here now we say context superheroes add and after that wait context save changes async all right and these are the changes pretty simple actually and now again in the controller we have to um at the oh wait keyboard here at least so here here and also here and now hopefully Visual Studio is telling us no issues found we save everything so we've got no warning no error whatsoever let's run this and make some tests and then let's think about relationships in Entity framework maybe we can add them too so let's just test this first again get superhero we should get two right there they are Spider-Man and Batman now let's get a single one try this out with id2 for instance execute we get Batman one we get Spider-Man and three hero not found great this works just fine now let's add one so we try this out we actually don't need the ID because well the SQL Server is doing this for us so Iron Man again Tony Stark and then Malibu execute and this is interesting we get Spider-Man and Iron Man all right let's have a look in the database okay I think I forgot something add hero superhero service oh yeah we returned the superheroes this is not correct what we want to return is awaits context superheroes to list async right this is what I want to return so let's uh copy this because here that's the same nope that's correct but here here we want to return them and here as well this is the if the add method so in the add method the delete method and also in the update method we want to change that and now we can actually remove this thing here yes build and apply changes do we really have an error now I saw an error here let's just reset the application and let's see try this out one more time execute one two and three great now let's try to delete Ironman for instance so 3 and execute gone and the database also gone perfect so now actually only updating is left so put try this out and you know I want to change Spiderman let me get Spider-Man first yeah that's the one see that because I do not want to override all the other properties don't need that and this is now oh all right grammarly it's Spiderman Spider Dash man okay now I may Zing Spider-Man execute and this looks great and here as well all right and now maybe just the add one more time let's just use it with the default values and we get id4 string string string and string grades and now regarding the relationships meaning maybe we want to add the teams or the comics or whatever it is so Spider-Man and Iron Man would be Marvel Batman would be DC for instance I don't know what string is maybe you know and for that we would add another model and add another migration and so on but I did this already in another video so just click on the video you see here on the screen and then you will learn the very next steps here
Info
Channel: Patrick God
Views: 126,968
Rating: undefined out of 5
Keywords:
Id: 8pH5Lv4d5-g
Channel Id: undefined
Length: 84min 26sec (5066 seconds)
Published: Wed Nov 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.