.NET 7 πŸ’₯ - ASP.NET Core Web Api CRUD, Repository Pattern, SQLite & Automapper

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign thank you for watching this video I am Muhammad and today we're going to be creating a full-fledged API but not we're going to be creating different endpoints with different Cloud operations we're going to be saving information in SQL light we're going to be utilizing unit of work we're going to be basically utilizing automaper to map different objects and we're going to be basically creating one single application for our API one class library for our data services one class library for our entities and we're gonna see how actually we can map everything together if you like this video please like share and subscribe it will really helpful Channel as well if you'd like to support me please consider supporting me on patreon or buying me a coffee now with that said grab your cup of coffee and let's get started just one simple note before we actually got started this application that we're gonna be building today is going to be the foundation of almost all of the other upcoming videos regarding web apis so instead of every single time coming through the same setup of creating the same application over and over again we're going to be utilizing this Foundation moving on as a foundation and from that moment forward what we're going to be doing is we're going to be basically adding a new function to it it is either going to be caching optimization more routing uh adding Docker to it etc etc etc so in this application that we're going to be building right now is going to be living with us through a lot of the upcoming videos and we're gonna be keep updating and changing it but it's going to be a solid foundation that we currently have in order for us to basically have a much more fluent development process for any new feature that we want to add now let's go back to the video so the first thing that we want to do is we want to create our solution then adding our API then adding all of the class libraries that we need in order for us to make our base application ready so within our terminal here we're gonna start by creating our solution we're gonna put dotnet new a salon and I'm just going to give it a name of Formula One and once that's ready I'm gonna start creating by my web API so that not new web API Dash on formula one dot API so that's going to be my API and now what I want to do is I want to basically add my application or basically my web API to the solution so in order for me when I open my solution my web API will will be added my class libraries so on so forth so every time I create anything I need to add it to the solution so everything will be linked together so let's see how we can do that so here all I need to do to add this I'm going to put dot nut salon Formula One and it's gonna be a DOT a salon add Formula One API formula on the Cs brush perfect that's the first one now I need to create my other class my first class Library so it's going to be let's clear this up so we have a clear view it's going to be not not new classlib Dash on and I'm gonna call this Formula One dot entities perfect now I need to add it as well so that not a salon add Formula One entities formula analysis yes approach perfect now let's clear this again and I want to add the last application a dust class Library so that's not new class Loop version I'm gonna call it Formula One dot data service perfect and I want to add it as well so not a salon formula wanted a salon add Formula One the data service perfect so now that I have created if I type let me clear this up if I type I'll ask now you should be able to see that I have three folders everyone related to the applications that I created so one for apis two for uh one for data service one for entities so two class libraries and one API and I have my solution file which is going to be basically which tying everything together so for the sake of this video what I'm going to be using I'm gonna use Ryder as my code editor in order for me to basically build everything there you can use any idea that you want you can use Visual Studio visual studio for Mac or you can even use Visual Studio code but for this video I decided I'm going to be utilizing a writer so let's see how we can open this up in Rider so I'm just gonna go right there and now as you can see once I open my solution I'm able to see my three applications so two console libraries and one API already perfect so all I'm gonna do right now is just I'm gonna run it just to make sure that everything is running as it should be and we can see here that everything is actually building perfect this is exactly what I wanted to say now I'm gonna close this and now I'm gonna start actually building my application so the first thing that I want to do I want to clear up my application because I can see there's a lot of generic file that has been created when I get my application I want to get rid of them so inside first my Formula One API I'm gonna delete the weather forecast I already needed so I'm going to delete this I'm gonna go to my controller I'm going to delete this as well because I don't really need it as well so let's go to edit delete perfect and inside my classes here I'm gonna also remove this so add it delete and inside the entities I'm going to also remove it so add it and delete perfect so now that I have done that inside my entities folder I'm going to create add a new directory I'm gonna call this DB set and inside my DB set I want to create few classes which can represent utilize inside my application so the first class is going to be called base entity is going to be inherited across all of the other entities then I'm going to create another class and this class is going to be called achievement and the last class is going to be called driver perfect so what I want to do here as well I'm going to directly inherit from that base entity to all of the other classes and now I'm gonna build up my base entity so install my base entity I want to create basically the information or the fields that's going to be shared across all so that's going to be ID created updated out and those basically made information the status and from there basically all I have to do is Define them once and I can basically inherent them into the other classes so here I'm going to start by first of all creating my good which is going to be my ID and I'm going to initialize it here then I'm gonna create another one it's gonna be created that what added that added date and let's make this as the first rank date time and I'm just gonna make it equal daytime.tc now and let's duplicate this and this is sort of at the date it's going to be updated date and lastly I'm just going to create the status field perfect so now that I have this now what I want to do is I want to build up my actual DB contacts objects so here I have driver and I have achievement so we're gonna start with a driver the driver should be pretty straightforward what I'm going to be adding here is gonna be first of all string which is going to be the driver's name so I'm gonna put first name and I'm gonna initialize it as well and I'm gonna put the last name and I'm gonna put that async number which is going to be in and I'm gonna make this as driver's number perfect and lastly I'm gonna add date of birth so I'm gonna put here date time I'm gonna put here date of birth perfect so this is going to be for my driver now let's update the achievements and for the achievements what do we want to track for this free driver it's gonna be basically and uh let's put the race ones so let's put here rice wins then I'm gonna specify another integer which is going to be Pole Position then I'm gonna specify here the fastest Club and of course the world championship how many world championship and I want to specify the driver ID so I'll go with that's going to be driver ID okay great so now that I have created my driver I have created my achievement the last item that I want to do right now is I want to link the achievement with the driver so I can have a primary care and a foreign key between those two entities whenever I create my application to be contacts in order for me to do that all I need is just to update both of these classes so they will know about each other and they will know how to communicate with each other so inside my achievements I'm going to add Republic virtual driver it's gonna be get and set and that should be it from here now inside the driver we need to update it first of all I want to create The Constructor and here what I need to do is I'm going to put public virtual High collection or achievement I'm just gonna call it achievements get that no way to initialize it inside the controller so I'm gonna put achievements equal a new hash that of achievements and that should be it perfect so now if I go back to my terminal here and I'm just gonna type dot not build you should build everything for me and I can see it build succeeded perfect and what I want to do is I want to install some packages inside my data service class library in order for me to create my application to be context and once I basically add all of these packages it's easy for me to utilize all of the DBC contacts functionality that's available for me out of the box through that packages so inside my terminal here I'm just going to navigate to my data service and I'm gonna start by creating the packages so let me clear this up see if I can make it this okay so the first package will be not add package Microsoft Dot entity framework core perfect let's clean this up the second one is going to be dot not add package Microsoft actually let's use uh utilize this last command Microsoft Entity framework core dot design instead of having us to retype everything let's clear this up and let's look design now we want to put tools perfect let's clear this again and instead of tools right now all we need to do is put SQL light because that's going to be the database that we're going to be utilizing okay perfect so now if I want to verify that everything has installed successfully if I go to the data service under edit I check my cs plus file and you can see here that all of the packages has been installed successfully perfect let's close this up let me clear this up and here all I'm going to do is I'm going to create a new folder a new directory I'm going to call it data and inside my data folder I'm going to create a new class and I'm going to call it up DB context perfect and inside my FTP context I'm going to inherit from the DB context class and you can see his directly reference the Microsoft anti-frame code so once I have done that the next step for me is I'm going to start initializing my models and as you can see from my video from the previous class library that we have driver and achievement so that's going to be the main tool that I want to add so it's going to be public virtual dbsat driver I'm just gonna call drivers get oops get unset and this pixels reference to automatically reference that application so that's good and then here instead of driver I'm gonna put achievement and I'm gonna rename this achievements perfect and now I need to initialize the Constructor so it's gonna be like this public Optical app DB context and here we need to specify the configuration so DB options for app DB context I'm gonna call it options and we need to pass it to the base class it's going to have options and here inside my Constructor and I'm gonna have not gonna do anything so I can just make it all on one line yeah and now I know I want to override function which is going to be let's see if we can automatically populate it on model perfect this is it public override on model creating so what I want to do here is I want to override a different implementation so I'm going to put model Dot oops what is it called model builder cellspot model dot entity and it's going to be for achievement and I'm going to specify the entity here I'm gonna start overriding it so now all I want to do here is I'm going to put I'm gonna fix this entity dot has one and I don't need this I'm just going to specify here I'm gonna put the 4D dot driver dot with many p dot achievements dot has foreign key again it's going to be the DOT dot driver items data driver ID and Dot on delete I'm gonna say delete Behavior dot no action and lastly what I want to do is I'm going to has constraint name and I'm gonna specify it as say achievements and Driver perfect and don't forget the semicolon at the end so what we did here is if we want to do a quick summary first of all we have defined the entities that we want to add so Define the DB entities and then basically here what we did is we have specified the relationship between the entities perfect and this approach is called code first approach because basically what we're doing here is we're utilizing C sharp chord and order for us to create our database to find the tables and Define the relationship between those tables and once we have done that now it's pretty easy for us to take it further by start actually implementing this inside our API and basically start worrying wiring it up there so we're actually able to create a database and basically start having our API and our database communicate with each other and basically acknowledge each other so what we need to do right now is inside my terminal here I'm just going to install a package inside my API so I'm going to go to formula Dot API and I'm going to put.net add package Microsoft Dot microsoft.ntt framework core dot design perfect and now I'm gonna actually start to populate this so inside my app settings I'm gonna create a new section for the connection string and I'm gonna call this default connection no one specifying my data source and I'm gonna call it up.db perfect so now that's done I can go to my program.ts and inject it here so before I do any build I'm gonna specify my connections string so I'm going to say connection equal Builder dot configuration Dot get connections thing and I'm gonna provide it the name and here it should be my default connection and now that I have that the next step for it it's gonna be building my application DB context so add DB should be add DB context I need to specify here it's going to be up DB contacts and the reason is being like this because I need to add the reference to the other project which I can do now and let's add this reference here perfect and now that I specified this now I specified the options that it's going to go to the Constructor and I'm gonna put options dot use sqlite and here I'm just gonna pass the connection string that I have perfect so if we're gonna do like a summary what I did here is going to say get conduction string and here initializing my DB context inside the DI which is stand for dependency injection container and basically I specify the options that I'm using sqlite with the connection string and if I go here we can see that these options are being injected directly here and being directly added to my patent class which is going to be the DB context perfect so now what I need to do is basically I need to first of all initialize my database using the commands the default code first database code first and then I'm going to utilize that from there the repository pattern in order for me to be able to communicate to my database and connect to it so inside my terminal here I'm just going to navigate back to my database service so inside my tablet I'm just going to type CD see the Formula One Dot database service and I'm gonna type the following so.net EF migration I'm gonna call this initial initial migration and I'm going to specify the startup project and it's going to be Formula One API so now basically this will be able to create my migration scripts and if you don't know what the migration scripts here is basically converting the C sharp code that we currently have into SQL code so basically right now whenever I run those migration script it will be able to be converted into SQL in order for my application to be sorry for my database to be created so if I take a look here right now inside my data service you can see that I have a wrong name inside migration I need forgotten us here so it needs to be migrations so let's make sure it's running we'll succeeded we can see the migration has completed successfully and we can see here inside my data service class Library I have a new folder called migrations and if I open this up we can see here that now I have my tables so I have my driver's tables my achievements with all of the information there and this is basically what I see here is gonna be the code for my sequence order for my database to be created and for my tables to be created are my primary keys and my foreign Keys between my tables are also then I'm created and all of that is kind of powered by the quote First that Entity framework provide for me so now that I have kept my migration now I need to apply it it's going to be pretty straightforward but not the f database update and I'm going to specify my startup project it's going to be the same formula of the API oops we have an error let's see what this error is I think my error could be here I forgot to put an S on connection strings so let me try this again and we can see it worked so basically here I put a conduction saying it should have been within us I know that's work I can see directly here on the left hand side I have app.db created and if I double click this connection perfect and if I click on OK we can see right now on the left hand on the right hand side I have my table and my application I'm sorry my database and if I click on servers we can see that I have everything here let me refresh and now I have my tables if I open my tables you can see here I have my achievements and my driver perfect so now that this is working as it should let me close this now it's time for me to create my my repositories so here all I'm gonna do is I'm going to get a new directory and I'm gonna call it repositories and inside my present studies I'm going to create a new directory as well I'm going to call interfaces perfect and inside my interface is here I'm going to create an actual interface and I'm gonna call it I generic depository and I'm gonna make sure it's an interface and I'm gonna create it and from here I'm going to add certain conditions I'm going to make it an anonymous interface and I'm gonna say where T is of type class and here I'm going to add the generic methods for my interface and let's see what I want to do so I want to have a task of I enumerable of object D and that basically return everything so I'm just gonna call it all and then I have another task 30 and I'm gonna say cut by ID and I'm gonna pass a good because I know all of my tables are gonna have a Google doesn't ID and then I'm gonna put task as Boolean and this is basically gonna be for adding I'm gonna make a t of type entity perfect task again bull and here I'm gonna say update 30. entity I'm gonna put task will and delete and here all I'm gonna take is another good type ID okay perfect so now that I have done that now I want to create an interface for my drivers so I'm gonna put I driver Repository it's gonna be of type interface and all I'm gonna do here is inhabit from the I generic repository and I'm gonna say it's gonna be a type driver perfect and I need to create another one for my achievements so I'm gonna put I achievements repo z30 that's going to be the same thing I'm gonna it's just gonna be an interface to the class and it's going to inherit from the eye generic repository of achievement perfect so now that this is actually uh cover the main two tables that I have now what I need to do is I want to add the implementation for these repositories so inside my root folder I'm going to add a new class and I'm gonna call it genetic repo it's a Terry actually before we do that I just remembered inside my achievements I want to add one method and it's going to be task it's going to do an achievement and I'm gonna cut driver achievement async and this is going to be based on the driver ID so go with right here and what I want to do as well is I want to create interface so I'm gonna create work interface straight forward I'm gonna have the eye driver s and I achievement Repository as well that's good and what I'm gonna do here I'm gonna specify the task which is gonna be called complete async perfect so this is what I need these basically I want to implement inside my unit of work once I get to it so once I have done that now what I want to do is I want to build my generic repository and this is gonna be also very fun to do so first of all I want to make it anonymous and I want to inherit from the I generic repository of type t as specify where T is of type class perfect and here is telling me that I have not implemented those methods so let us put them all here so now you can see I have my old got my ID add update and delete so here what I'm going to do is I'm going to make sure that this is async actually before we do that let us connect our application DB context so I'm gonna make it public first of all let's put the locker read on the eye logger blogger that is going to be protected for now and I want to have an internal DB set of type t and here I'm going to specify my DB set and then I'm gonna have a Constructor here and inside my Constructor I'm going to initialize all of these so first of all guys you know this is my app DB context I'm gonna let's make this underscore TV context so here's gonna be context but underscore DB context equal contacts perfect that's the first one then what I want to do is I want to specify my DB set so I'm gonna actually let's put the loggers idb I logger logger let's make this underscore actually listening yeah let's make this underscore and we're gonna put underscore blogger equal blogger perfect now I want to set my DB set so I'm gonna put DB set equal context dot set and here I'm going to specify a set of d and I think the RC needs to be Capital so let's do it like that okay perfect so now that I have done this why is this one is not happy what is it saying it's fine so now that I have done this now let us start implementing it all actually let's keep that all as chair as unimplemented so we can implement it one by one but that does get by ID so here let's change this to async and let's just remove this and add the proper implementation and it's going to be pretty straightforward I'm gonna put return oh wait TV set Dot point async and I'm gonna pass the ID so that should be pretty straightforward and I'm gonna make this as a nullable so that means that I need to update my repository to be notable so let's go to that and I'm going to make this as notable as well perfect let's close these okay so that's gonna be the first one I'm just going to implement the second one is going to be the add so let's remove this and if the ads going to be also pretty straightforward I'm gonna put a weight underscore DB set dot add entity oh this needs to be at async perfect and this needs to be facing and lastly we're gonna have to return through perfect so now I'm just gonna go back to my API so let's clear this up see the Formula One API I'm gonna put dotnet build just make sure everything is building okay great build succeeded that's exactly what I wanted and now what I want to do is I want to implement my driver repository so I'm going to add a new class and I'm gonna call this driver Repository and it's going to be also pretty straightforward so the driver repository is going to implement the I generic sorry it's going to put on generic repository for driver as well it's going to implement the eye driver repository so both of them so let's fix this reference here perfect it's going to tell us that we did not Implement so not missing number and here we can see basically it directly initialized my Constructor which is exactly what I wanted and I'm gonna now specify the all so I'm going to put public override async task I enumerable driver and I'm gonna say it's gonna be all and now we can specify let's see why is this is not happy okay what did I call it maybe I did not call at all I called it all okay let's continue and then we can see so here I'm gonna put my tricots and let's start with the try so I'm gonna put return await underscore DB set where say X dot status equal equal so I don't have this so I'm just gonna put it now one for now which basically it means active and I'm gonna put dot as no tracking because I don't want it to be I need the framework to track it I'm gonna put as a split the query in case it's a very but big return that I need and I'm gonna order by order by the other date and lastly I'm gonna make it as a to list async perfect and now here what I want to do is for my exception in case anything goes wrong I want to First make sure it's in the logger so I'm gonna put underscore Docker to block error and I'm gonna pass here my exception which I think it's e and then here I'm gonna pass my error message so I'm just gonna say this is going to be my repo I'm gonna say all function error and I'm gonna add here my name actually it's going to be pipe off and type off and here we're gonna specify the driver Repository perfect and basically lastly instead of throwing I'm gonna yeah let's throw it and here let's see oh we did not make it as a virtual that was one of the main issues so let's fix it right now so the painting is I want to override it it makes it really easy okay perfect so now that I have created my all the next one is gonna be my delete so I go in public override async task bull the heat that's gonna take a good of ID again try cut let's just let me copy this instead of me typing it all over again and here I'm gonna say delete and so the fall and here what I want to do first I want to get my entity so I'm gonna put for results equal await underscore DB set dot find async actually we can make it easier dot where actually we can make it first or default async I recommend it by the ID and we can say equal equal ID if result equal equal null maybe we didn't find it we return false belts we put results dot status equals zero means deleted result Dot update date equaled date time now Dot UDC now actually not instead of now and that should be it and then we put return through perfect so that's the delete and lastly let's do the update so public override facing task Boolean and we're gonna say it's gonna be the update and we're gonna take a type of entity which is gonna be driver I'm gonna call it driver and again try I'm gonna copy this and here it's going to be update and what I want to do here is when I follow the same logic so I'm just gonna get this and here it's gonna be driver.id and I'm gonna say here in case that my result equal no longer return false else I'm gonna put the result dot updated date equal daytime the TTC now result Dot driver number equal driver the driver number result Dot first name equal driver DOT first name result dot last name equal driver dot last name result dot date of birth equal driver dot date of birth and lastly I'm gonna put return true perfect again we're just gonna do homemade.net build just to make sure everything is still building nothing is crashing and as I can see here the build is succeeded and now once this is done I'm gonna move to the other repository which is going to be my achievements so again I'm gonna create here a achievements Repository again for the achievement achieve I forgot the e and as updated here edit rename .d here and once I do that all I'm going to do is basically similar to what I have done here I'm just gonna take this and I'm gonna update for the achievements so instead of inheriting from a driver it's going to be from Achievement uh sort of iDrive it's going to be I achievement Repository and this is not happy because I did not Implement all of the functionality similarly here perfect so here we can see that automatically added my Constructor and in order for me to initialize all of what's needed and this is my custom method which is going to be get driver achievement I think so let's do this first let's convert this to an async here and it's going to be pretty straightforward I'm gonna put try catch let's take the same other structure so let me just copy it and update it the achievements here and here's the driver repository is going to be achievement Repository and this is called cut driver async so let's make it like this perfect and here results underscore oops dbsat Dot first or default I think no let's go and try to match it by driver's ID equal equal driver ID and that should be it actually I must return it and this one needs to be a nullable so let's make sure this is not a build and we go to our achievement and let's convert this to nullable perfect so now that I have done that what I can do is I can simply copy the One for All and for the delete and as well for the update and we can update it there so I'm just gonna copy them and update them here so let's start first by the all instead of driver I'm gonna put achievement so you can see everything should be working and here it should be driver repository which is fine we need to change it to achievement Repository okay great so now this is working and the all should be all the same that's fine the delete should be also all the same which is fine and here I have my update and this needs to change it's not driver it's achievement and I need to change here from driver to achievements and let's copy this and this one is not achievement repository is actually achievement so that's why not us put an ID here perfect so now all I need to do is just update this information so for achievements what I have here is first it's gonna be the fastest lap so let us update this equal achievement dot fastest lap resolved oops result Dot Pole Position equal achievement dot wall position I have resolved dot erasewinds equal achievements dot race wins I have result Dot World Championships equal achievement Dot World Championships and that should be it for my achievement repository so I'll put.net build perfect I can see everything is working great so now what I need to do after that is I need to build my unit of work so I'm gonna add here unit of work and basically what I need to do first of all is I need to unhide it from the i unit of order that I created previously so first of all it's going to be private read only I have to be context and we're gonna call it context and then it's gonna be a public eye driver repository there'll be drivers get then we're gonna put public achievement Repository achievements and I got now and specify my Constructor and the Constructor is going to take two things first of all it's going to be my app DB context context and my eye logger Factory perfect I'm gonna call it logger Factory and now I can initialize it from here so it's going to be the underscore context equal to contacts it's gonna be creating a locker and this Locker is going to be equal to loggerfactory dot create logger and I'm going to call this locks perfect and now what I can do I can put drivers equal new driver repository and I'm gonna I can pass the context and I can pass the logger great and I can do the same thing for achievements it's going to be achievements well it's going to be equal to achievement Repository similar things so now that I have initialized these I still have two things that I need to initialize first of all it's going to be public async task complete async and here always going to say await underscore contacts dot save changes I think actually we can make the small of a Boolean so we can make sure it actually worked well update it but basically what we can do here we can put forward result equal and you can say return result if it's bigger than zero it means that it is success because if it's equal to zero or less it means that it failed and lastly what I want to do is I want to add my garbage collector so I'm going to put public for it suppose so that made it to dispose for anything which is loosely created I wanted to do is dispose and I'm gonna add here also High disposable perfect and now let's update the unit of work so this will return actually a response so I'm gonna put go to and here the complete async is going to return a Boolean perfect so now that this is done the student not built first of all let's clean it up dot nut builds and we can see that everything is building successfully perfect so in order for me to wire this up what I can do is directly I can inject my ioni defer interface and my unit of fork implementation into my program.ts inside my API in order for my di container to actually recognize them and so I can able to utilize them inside my controllers so let's see how we can do that so inside my program.cs what I'm going to be doing here is before the actual application builds I'm gonna put Builder services dot add scope and it's going to take the i unit of work interface and the implementation for a unit of work oops unit of work and that should be it so that's mean right now my repository should be active within my application so now that's done now I want to think actually about my implementation for my controllers my dtos and basically my mappers so the next step is once I have set up my database the next step right now is I need to basically think of my mappings inside my controllers I actually think about the controller implementation so basically I don't want to use the object that I have created for my database as a way for my clients to communicate with my API so what I want to do is I want to create some kind of an API models and that's called dtos I want to create certain dtos which basically allow the consumer to send specific requests and these requests are going to come to my API they're going to be mapped to my objects for my database and then they're going to be utilized inside my repository to be added so what I want to do is I want to create this layer in order for me to separate my database entities with my with the entities that the actual clients will be utilizing and it's really important as part of my separation of concerns that I want to actually Implement within my apis so let's see how we can Implement that and before actually we do that we need to actually think about the mappings and that means of how are we gonna actually translate that client model to my database model and in order for us to do all of that we can actually utilize a library called automaper which will automatically map all of the different objects from one object to another it will save us a lot of time trying to do those mapping manually and we're going to see all of that how we can actually implement it right now so let's start by installing some of these packages that we need and other Foresters of the mapping I'm going to put that nut add package Auto mapper perfect and for ad and other thrust utilizer with dependence instruction media we need to install another package it's going to be.net add package Auto mapper dot extensions dot Microsoft Microsoft dot dependency dependency instruction perfect and now once I have done that inside my program.cs I need to initialize it so I can do it here we can put builder.services Dot add automapper and we need to identify what it's going to find at the DLS in order for it to be actually able to do the mapping so we're gonna put uh domain Dot current domain dot get assemblies and that's basically what it does is it allows us to actually scan all of the dlls it's gonna find those with all of the objects inside and once it able to fire them if whenever we have any profile for mapping one object to another it will be able to automatically recognize it at runtime so that's the powerful thing about it and because here we have added into the depends to the eye container we're able to directly access it so once we have done that now what I want to do is I want to start building my controllers so inside my controls folder I want to create a new controller and I'm just going to call it base controller foreign that I have here a base controller is in order for me to have a controller where I put all of the configuration in and all of the other controllers will be able to inherit from that controller rather than having this configuration repeated over and over again or on every single control that I create so I can hit them in one single controller and from that I can inherit this configuration to all of the other controllers and this main controller I'm calling it bass so I'm gonna start first by defining my route to it and now it's going to be pretty straightforward API forward slash the controller name and then I'm gonna specify this is an API controller um I'm not sure why is this happening so let's put it like this okay perfect and now here I'm just gonna inherit it from controller base so now I wanna what I want is I want to initialize my application DB context so it's going to be protected read only well actually let's initialize the ionet of work I call it unit of work and then I'm gonna initialize protected hit on the eye mapper which is gonna be if uh utilizing the automaper I'm gonna put mapper here and then I'm going to specify my Constructor and inside my Constructor first of all the unit of work and my mapper and then directly initialize them inside my Constructor perfect so now that I have done that I have created my base controller so the first thing that I want to do is I want to create my driver's controllers and here all I'm going to do is I'm going to inherit from the base controller and we can see here standing indeed to implement all of the stuff so let's Implement them and this is done and I'm going to create my achievements controller and again I'm gonna inherit from the base controller it's going to ask me to implement everything and everything is implemented okay perfect so now again I did not build so now what I'm gonna start first is I'm gonna create my objects which is again that clients gonna be able to send me an order for me to either update my achievements get the drivers on so forth so I'm going to start getting by these objects and these objects are gone called DDO data transfer objects and basically from there uh once I have them I'm gonna be able to actually do something inside my controller so inside my uh Formula One entities I'm gonna create a new for directory I'm going to call them DDOS and I'm gonna separate them into two folders so the first one is going to be called the responses which is everything that the API will send back and the other one is going to be called the requests and under the request one I'm gonna create a new class or new dto I'm gonna call it create driver achievement Quest and here it's going to be pretty straightforward we're gonna have basically the good for the driver and then we're gonna have prop integers I'm gonna put world championship and then I'm gonna put first slab then I'm gonna put forward position and lastly I'm gonna put winds which is going to be for raisins perfect and now I'm gonna create the response this is gonna be almost identical to this it's gonna be driver achievements response and I can just take all of this information because this one I'm going to be sending back again the reason that idea are separate in order for me to basically have the flexibility to update them but for now it should be completely fine to have them almost similar once these dtos are created what I want to do right now is I want to create the mappings utilizing automaper so inside my API I'm gonna create a new directory and I'm going to call this profiles I'll call it mapping profiles inside my mapping profiles I'm going to create a new class and this class is going to be a domain to response and there's going to be another one it's going to be called request to domain perfect so we're gonna start by request to domain and the request automation should be pretty straightforward with basically taking the request and made basically mapping it directly into the object so everything inside the automaper it needs to happen through the Constructor so here I basically you can see I have initialized it the class needs to inhabit directly from the profile and you can see it's basically from automaper similarly to the other one with the heard from profile okay perfect now inside the requested domain what I'm gonna do here is I'm gonna specify a map so I'm gonna say create map and here inside the create map I need to specify from what to what so I'm gonna say it's gonna be from create driver achievements request to achievements this is going to be the main mapping that I have and then here I'm gonna specify right now the mapping so I'm gonna say phone number I need to specify the destination I'm gonna put destination.tracements equal it specify the options so race so I'm gonna put the options and options dot map from and here is going to be SRC and SRC dot wins so why are we doing this because if I take a look at why create a driver achievements request you can see here this is called wins when I look into my dto sorry my database object inside achievement it's called the race wins and what I want to do here is I want basically a way where I can notify Automotive that this field belongs to this field and basically once I do that inside the profile whenever automobile sees these two objects it will automatically map these two Fields together without me having to do all of this manual mapping manually again so once I said that once in the profile it will be available for me anywhere that I need to use it so this is the first one so let's go back from here and we can see that this is actually added so now I need to add another one which is going to be four actually I need to close it so now this is going to be the first one then I'm gonna see oh need to close it twice and then I'm gonna put dot four member now I need to start to put the other ones so let's get again for destinations and for the destination I'm gonna put dot status so I directly want for every single request coming in you I just want to specify a new status and for the options I just put opt similarly it's going to be opt dot map from and here instead of relying on that object I'm just going to say it's equal to one so what I can do is I can put SRC and as RC is going to be equal to one perfect now the other item that I want again for remember and it's going to be destination and this is going to be destination dot edit time now the date and here we're going to stimulate options so opt oops this needs to be a comma I'm going to put opt .map from SRC SRC Dot so it's going to be equal to date time now dot UTC now perfect so once I have done that the last one is going to be for remember destination let's put it on a new line destination destination dot date updated date options again opt from SRC SRC Dot date time actually as date time dot UDC now and at the end of this a semicolon so that's going to be the first mapping which I'm going to be doing between creative driver achievements and achievements and the other one is going to be from the so we have created the create I think we also need to have the update and then we can do the mapping because the update we don't really want to do all of these where is it we don't really want to do the added date and the status because they are already set all we need to do is set up the update date so here what I can do is I can just copy this and sort of create a driver we'll say updated driver achievements and here instead of create it's going to be update driver achievements and if we go back to my to my profiles I can just copy this so instead of create it's going to be update driver and we didn't further update I don't need the status and I don't need the data added so we can remove them directly from there okay perfect now I have only two great so now that I have created these I have created the mappings I have created my achievements next step is I want to build my achievements controller I have already started here but let us take this a step further so first let's do some refactoring so everything will fit on a single page and then now I want to do is I want to start by getting my driver achievement so I'm gonna put tasty pig at and here I'm going to specify my route and it's gonna be driver ID and it's going to be of time go with and then here I need to specify public async task I actually resolved it's kind of got driver achievements and it's going to take a good as a driver ID and what I can do here is going to put VAR driver achievements equal await underscore unit of work dot i achievements don't get driver achievement by the async and I'm gonna pass the driver ID here and I'm gonna say if driver achievements equal equal to null I need to check if a driver exists so I can put the file driver equal actually what I can do is just return return not found as simple as that I can put a message yeah I don't want to give a lot of information on this URL and then I can put if I can actually else what I'm gonna do is I need to map out the response so now what I'm going to put this word result equal equal underscore mapper dot map driver what did we call the response driver achievement response from driver achievements so what we're doing here is basically we are calling by the auto mapper I'm telling it to map uh I'm basically I'm trying to get about everything from the achievements we can see this achievement to the object dto that I have I just realized that we did not fill in the profile for the response which we'll have to do right now because it's going to be domain to response I will not do it we'll do it right now after we finish from this controller so if I go back to this controller here after we have done that what I'm going to do is I'm going to put return okay with that result perfect so now let us do the other Auto mapping so here I'm gonna be from the main to response and it's going to be similar to this all I'm going to do is Constructor and then create everything there so I'm just going to copy these and update it as I go actually the last copy all the way to here because it's easier and then we can update it so here what I want to do is first I need to update the constructor's name and then it's going to be from achievements to Squad driver achievement response so we're gonna put driver achievement response and we can see here from Achievements not code race wins it's called wins and it's gonna come from racewinds and we need to fix this first let's fix it okay and this is gonna be dot race ones perfect I don't need status do not needed other date I don't need it and updated date I don't need it perfect so that should be sufficient and now if I put.net build we can see it is building successfully and now let's see if I can run it what happens we have an error let's see what this is error I have an issue with the routing let's see here wrote template API oops I forgot to close this here okay let's try it again perfect it's running on this let's get this here and as you can see I have my one API ready and now it's going to ask me for the driver ID I don't have any driver ID so I should get a 400 so if I put one it must be a valid to go with uh let me find it Well actually as soon as I can see it right now it's fine once I have the information I can continue but at least I know that my application is actually running as it should be because I can able to see the endpoint that has created perfect let's go back to Rider let us stop that and let's continue so now this is for the achievements now I want to do is I wanna do a creating of the driver achievement so this is going to be http post and let's do the templates gonna be empty and this is going to be again public async task I action resolved and we're gonna say here add achievement and we're gonna say it's going to be from buddy create driver achievement request I'm gonna call it achievement I think that should be enough and here I'm going to say if not equal model state is valid I'm gonna return bad request which means that the crossbody which is coming in is not valid so I'm just say it's going to be a bad request so I don't have to progress the request any further if everything is fine I'm gonna put the third result equal I'm gonna map the incoming dto to an object detail for my database dot map and here basically I'm going to specify it's gonna be transferred to an achievement from my create driver achievement request and once that is done all I'm going to do is await underscore unit of fork.achievements dot add and I'm gonna add the result and then I'm gonna put a weight underscore unit of work dot complete async and then what I'm going to do here is return okay actually I'm gonna return the created at action and we're gonna start first by name off it's not does not exist yet but actually got driver achievement yes we have created it oh yes so that should be fine and then I need to specify my ID so this is going to be driver ID so put driver ID equal result Dot driver ID and last year we're gonna pass that result perfect perfect and the last one is going to be the update so HTTP put again it's gonna have empty template and a republic async task I actually result it's gonna be update achievement again from body and here we're gonna put the update driver achievement request I'll call it achievement similar to what we have done before if not equal model state that is valid return bad request else were results equal underscore mapper dot map achievement with achievements so we're converting it from update driver achievement request to an achievement and then from there what I'm doing is I'm gonna just update it so I'm gonna put a weight underscore unit of work Dot achievement.update and I'm gonna put the result and await underscore unit of work to complete async and Dusty I'm gonna return no content this is basically the response type whenever I have a update so let me start on this again we can see I have my gut my post and my put okay perfect so now the next step is I want to cater drivers in order for a meter to actually create achievements for them so I'm gonna stop this right now here and I'm gonna go back to my dtos and inside my dtos here I'm gonna create one for drivers so it's gonna be great new class I'm gonna call it to create drive and request and it's gonna be pretty straightforward so prop string first name and I'm gonna initialize it equal string dot empty let's update this to last name then I'm gonna specify the driver numbers it's going to be an end and I'm gonna put here a driver number it's not a string so we don't need this and lastly I'm gonna put prop daytime I'm gonna put here date of Perth okay perfect so this is for locator driver now for I'm going to take this and I'm gonna create another one I'm gonna say update driver request I'm gonna have the similar information there but the only thing here I'm gonna add is going to be a good with the driver ID and now I'm gonna create a response and the response here is going to be get driver response and basically what I want to return is crop good driver ID I wanna return their full name rather than first name and last name by itself actually it's going to be string and this can be initialized equal string dot empty and then I'm gonna put public and driver number get that and lastly public daytime I'm gonna put here is gonna be the date of birth again similar cut and sets okay perfect so now that I have done this I need to go back to my Formula One API and inside my profiles I need the other profiles for this so I'm gonna start from the domain to the response it's going to be a bit straightforward so it's going to be create map from driver two driver what did I call it driver let's see what we call it that's it I misspelled it here so let's edit it out rename gut driver get the driver response so here it's gonna be cut driver response and I'm gonna put dot for member and here we're going to put destination destination dot full name and we're gonna put the options options Dot map from SRC and here we can use string concatenation we're gonna put src.firstname space SRC Dot classname perfect so that's going to be the first one for the mapping now I can do the other one which is going to be the request to The Domain to response oh I forgot to close it so let's just add a semicolon and now I'm going to put the request to domain as well pretty straightforward stuff the first one I'm going to be create map and it's gonna be create driver request to driver and then it's going to be from dot four member and we're gonna put the destination destination.status options options.map from SRC one again dot for member now let's do the dates actually let me copy paste them because it's easier than trying to and for the updated so copy these put them here perfect now let's do lastly let's copy this for the updated driver so instead of create a driver we're gonna put the update driver and for the update all we need to do is just update the update date so we don't need any of this perfect so let's go back to our terminal and my favorite command does not build let's see how it turns out perfect we can see here everything is successful so once we have done that let's go to our driver's controller and start building it up so first thing is going to be the HTTP get and let's specify the route and the template is going to be driver ID actually it's going to be the other hyper ID let's go with that's going to be public async task I actually result get driver it's gonna be good driver ID output file driver equal underscore actually await underscore unit of work dot drivers dot Gap by ID driver ID F driver equal equal null return not found if it is not if it's not actually if it does exist for result fees of equal underscore mapper.map to driver response and it's going to be from driver and what I'm going to turn is return okay with the results perfect so that's going to be the get next is going to be the post so HTTP post again it's going to be empty and public async tusk I accidentally solved the driver it's gonna take from body driver relax fix those references perfect and here I put F underscore sorry model state DOT is valid is not true return bad request simple as that else for result equal underscore mapper.map to driver actually this one is going to be driver for creation driver what would we call it create a driver request perfect from driver and then I'm gonna put a weight underscore unit of work the drivers.add result oh wait underscore unit of work complete async and lastly I'm gonna return the Creator that created that action and it's gonna be got name off and it's going to be the get driver let's recall that get driver under me to pass the ID so new driver ID equal result Dot dot ready and Rusty the object which is going to be result okay well actually here it would be good to convert back the object into a dto but for example this is the sake I'm keeping it as is the last one is going to be put and then we're gonna have delete and I got all so let's see HTTP but again empty template public actually let's copy it doesn't updated a bit faster so a set of a driver is going to be update driver instead of created arrival request is going to be update driver request instead of ad is going to be update instead of returning all of this we're gonna return your content and everything work fine perfect that's for the drivers now let's do the get all and just copy the get by IDM you can update it so let's copy this and I'm gonna remove this I don't need it and I'm gonna call this skit all drivers don't need driver ID login driver ID and got button by ID I'm gonna say all we don't need this and instead of returning one object I want to create AR enumerable off what was it called I enumerable I've got driver responses and that means it's got convert it into a list and that should be it actually you can make this a bit smaller let's remove this put it here I don't need this two lines you can even make it one but today is a bit more clear and lastly we're gonna do the delete so we're gonna put http delete we're gonna specify the route it's going to be driver ID go ahead of this and then public async task I actually resolved delete driver go with driver ID for driver equaled the score actually await score unit of work the drivers.cut by ID when I we need to make sure it exists F driver equally equal null return not found I'll see if it does actually exist we're gonna return we need to delete it so we're going to put a weight underscore unit of work to drivers.delete other than the past ID oh wait underscore unit of work dot complete async and lastly return no content perfect let's start it right now so let's start this let's close this let's close this and let's get a driver so driver post try it out first name Lewis Hamilton 44 let's put any date let's put 1983 something like that and we can see it has created successfully we got a 201 and we got everything here and we got the ID perfect let's take this and it even gave us the full location if you want to find this driver perfect so now that I found this let's try I think a driver what id try it out specify the driver ID execute and we got everything here we can see that you have a problem with the driver ID so let's fix it let's go back to Rider and let's take a look at the mapping that we currently have where is it where is it so we have the mental response and here we need to add one for the ID so we can put dot four bumpers destination destination but driver ID options we need the other comma options options Dot map from SRC SRC Dot ID src.id perfect that should work so let's stop this run it perfect let's come back here should be open here and let's execute this again and you can see now we got the ID perfectly so now that I have this what I want to do is I want to create an achievement post try it out I'm gonna put the driver ID that I have erase it again so World Championship seven although it needs to be eight fast step 104 fourth position 104 nope full position I think 63 and when this is going to be 104 or 103 I think execute now you can see it's created successfully I got the driver ID I got my ID perfect so now if everything goes to plan if I get the achievement for that driver should be able to see the exact achievements and as you can see here I got my driver ID my world championship first slab perfect and this basically right now it means that I have a full working API with Entity Framework with Entity framework with automaper with unit of work and with a good implementation of separation of concerns so this application that we currently create is going to be the basis of all of the almost all of the future videos regarding apis when instead of having to go all of the money works every time but to create an API we're going to utilize this and build on top of it either for caching either for optimization either for adding new Services etc etc and this is going to be our main application to do so it has all of the information that we need it has a SQL light as a database it has Entity framework already wired up and we can basically scale it up as we need to I hope this video was helpful well let's do a quick recap of what we have covered today so the first thing that we did today is We have basically created the applications which is three where the API the data service and the entity we connected them to a single solution then we have started by building the entities we added the DB set we created the base entity which kind of contain all of the main information we created the driver and the achievement entity once that has been done inside the data service we have created our application DB context where we have set up everything that we need and then basically we have provided up into our API and then basically we have created the conduction string and then from there we have wired it up into over the eye container so we'll be able to utilize it once we have done that then we have started working into the repository pattern where we have created the repositories that we need and the unit of work once once that's done again we have mapped everything here and then once we have done all of that we started working our dtos and our controller to make everything is working as it needs to and then now we have a full application ready for us to utilize anyway that we need and to build upon I hope this video was helpful if it was please like share and subscribe it really helped the channel if you have any questions please put them in the comments down below and we'll be more than happy to help again thanks very much for watching and have a great day
Info
Channel: Mohamad Lawand
Views: 7,835
Rating: undefined out of 5
Keywords: .net, api, c#, dependency injection, entity framework c#, entity framework, asp.net core tutorial, .net core, asp.net core, web api, dotnet core web api, dotnet core, dotnet performance, dotnet core elasticsearch, dotnet configuration, how to code, dot net, sqlite, entity framework core, automapper c#, automapper in asp.net core 6, automapper c# asp.net core 6, repository pattern, repository pattern in asp.net core web api, repository pattern c# web api, dotnet sqlite
Id: NNiupSwiVfg
Channel Id: undefined
Length: 95min 38sec (5738 seconds)
Published: Sun Aug 20 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.