Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

Junte-se a nós no Amazon Web Services re:Invent 2024! Saiba como usar o MongoDB para casos de uso de AI .
Desenvolvedor do MongoDB
Central de desenvolvedor do MongoDBchevron-right
Idiomaschevron-right
C#chevron-right

Começando com o novo provedor MongoDB para EF Core

47 min • Publicado em 15 de dezembro 2023
.NETC#
Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Vídeo
star-empty
star-empty
star-empty
star-empty
star-empty
Pesquisar
00:00:00Introdução ao MongoDB EF Core Provider
- euntroducteuon to the new MongoDB proveuders for EF Core. - Overveuew of the tutoreual 's objecteuves and prerequeuseutes.
00:01:37Configurando o EF Core com MongoDB
- eunstructeuons on setteung up the project and addeung necessary NuGet packages. - Confeugurateuon of MongoDB setteungs eun appsetteungs.json. - Explanateuon of createung the DbContext and euntegrateung eut weuth MongoDB.
00:13:01Implementação de serviços
- Createuon of serveuce eunterfaces and eumplementateuons for car and bookeung enteuteues. - Dependency eunjecteuon setup for serveuces eun the program feule.
00:22:50Criando Modelos de Visualização
- euntroducteuon to veuew models and theeur role eun the appleucateuon. - Createuon of leust and add veuew models for cars and bookeungs.
00:25:31Controladores de construção
- Development of controllers for car and bookeung enteuteues. - Explanateuon of CRUD operateuons weutheun the controllers.
00:32:42Desenvolvendo visualizações e páginas do Razor
- Createuon of veuews for leusteung, addeung, edeuteung, and deleteung cars and bookeungs. - Setup of Razor pages to eunteract weuth the controllers.
00:42:46Testando o Aplicativo
- Demonstrateuon of the workeung appleucateuon weuth CRUD functeuonaleuty. - Troubleshooteung and feuxeung an error related to the car leust veuew model. - Feunal walkthrough of the appleucateuon 's features and operateuons.
O foco principal do vídeo é aprender a criar um aplicativo de pilha completa usando o MongoDB com o EF Core no .NET, abrangendo a configuração, os serviços de back-end e as exibições de front-end para executar operações CRUD e o controle de alterações.
} Pontos-chave
  • Introdução aos provedores MongoDB para EF Core, atualmente em pré-visualização.
  • Guia passo a passo para criar um aplicativo de pilha completa com operações CRUD e controle de alterações.
  • Explicação das ferramentas e pré-requisitos necessários para seguir o tutorial.
  • Passo a passo detalhado da configuração do EF Core com MongoDB e implementação de serviços e modelos de visualização.
  • Criação de comandos e visualizações para lidar com interações com usuários e apresentação de dados.
  • Demonstração final do aplicativo de trabalho com funcionalidade CRUD.
Todos os vídeos do MongoDB

Transcrição completa do vídeo
hey friends you may know that for many years now we have had a mongodb driver for.net but did you know that we recently announced the mongodb providers for EF core to give support to EF core and it's currently available in preview I'm lose Carter a developer advocate here at mongodb and in this video tutorial we're going to go ahead and use asp.net MVC and the new EF call provider and we're going to create a full stack application with crud and change tracking so let's get started in order to follow along with this tutorial you're going to need a few things Net 7 a basic understanding of asp.net MVC and C a free mongodb at this account and an m0 free tier cluster and visual studio 2022 I will be using it on the Windows platform because that is the most commonly used but if you wanted to you could of course follow along using the net CLI instead and visual studio code with the cop dev kit extension or visual studio for Mac of course your experience if you do it that way will be slightly different but on the whole it's fairly simple and all the links that you'll need can be found in the video description below so let's create the project so here we are in Visual Studio 2022 and we're go ahead going to go ahead and select create a new project that will then bring up lots of different project templates that you can pick the one we want to do that you can search for is asp.net cor web app model view controller select it click next then we want to give it a name so we're going to call it super car booking system it's entirely up to you whether you choose to place a solution project in the same directory I do it just because I don't like it to create an extra folder but it's all down to preference click next uh then pick your net version from the dropdown I recommend picking Net 7 here authentication type is n uh make sure that we configure it for https and leave the other options unticked then we're going to go ahead and click create so that will build out our project and it'll be the standard out of the box asp.net MVC application that you'd expect so now we're going to go ahead and add the new mongodb provider for EF core driver into our application now that we have our project created it's time to add the new get packages so we'll right click and go to manage new get packages going to go to browse make sure they include pre-releases ticked otherwise you won't see the driver because it's still in preview so we're going to type mongodb Entity framework core in the search box select Entity framework core and install the latest pre-release which at time of recording is preview one so accept that the other package that we also need to install is ND framework core itself so also search for that and because we are targeting Net 7 we are going to make sure that we select 7.0.4 from the version box so select that install it accept the terms and conditions and there we have it now that we have the new get packages and the project setup and everything it's time to start adding the models that we're going to use two of these models the car and the bookings will represent uh documents in our collections in our database and then the third will be to represent our settings all the all the codes I be using today will be copy and pasted from the written version of of this tutorial which you can find by following the link in the description below so first of all we're going to start off with the car booking so we're going to to add a new class to our models folder we're going to call it car then inside of that we're going to copy and paste some using statements at the top we're then going to copy the class decoration and some properties and I'll talk through them so here we've got the class we've got an attribute on it that's just saying that this model class is mapping to the collection cars in our database so this is coming from the mongodb driver then we've got an ID which is a type object ID which if you're familiar with mongodb is our uh data type that looks a bit like a guid that we use for our _ ID primary key field then we've got the model we've got some um bit of error handling and um sort of prettifying stuff that comes from asp.net then we've just got a couple more properties so number plate location and then a Boolean whether or not the car is booked so we can save that and now we can do the booking class so we can add again a new class I'm going to call it booking I'm going to copy the whole classes time because it's all very similar so just like before we got the same using statements we've got a collection attribute but this time it's for bookings then we've got the extra properties because we want to reference a car ID with a booking we've also got here again with the object ID and that will match to the object id id field from the car model and then we've got some uh date time FS here for start date and end date of the booking so save that and then last but by no means least we're going to add the mongodb settings class so this is just a class to represent our settings that we will store in app settings. Json later on so we're going to call this mongod DB settings we're going to copy that I'm just going to replace this here so this has got the attributes um as I say that will come from our app settings so we've got the atlas URI which will be your connection string and then we just specify the name of the database and we'll use that later on when we get the settings from app settings so save that so now we we're good to go and we can start setting up EF core next nice setting up EF core with a new mongodb provider for EF core is very similar in fact almost identical to how you do it with something like SQL so a lot of this may look familiar to you so the first thing we're going to do in our models is we're going to create a um folder actually know what we're not going to do it in in models we're going to do it inside of a new one called services so we're going to add a new folder called services but again where you put this is entirely up to you this is just my personal choice then inside of services we're going to add a new class we're going to call this car booking DB context it's going to extend DB context so again it's just the same as standard EF core this is nothing new then we're going to add our DB set so this is the set of of sort of properties documents models whatever you want to call it for our database in EF core so we're going to call it cars do a getter and Setter doesn't know about cars yet so we can add that using statement then we're going to do the same for DB set of bookings the booking bookings get and set there we go next we're going to do the Constructor for the GB context so that just takes the options and passes it to bass but we're not going to do anything with that and then we're going to uh pay some code which overit a uh method you might know well which is on model creating so we're saying pass in the model builder then the model builder we're going to create a model builder entity for car and for booking now if you've been doing this with SQL before you might be used to seeing things like the table here which is a SQL thing mongodb driver does also support to collection so you could do collection and the name of the collection the reason that we're not doing that here is because we added that collection attribute in on top of the model here like so so you can either add these attributes to give the name of the collection here or when you create the DB context you can pass it here in the on model creating so so that'll go ahead and create our models for us and that's all we need to do for the card booking DB context the next thing we need to do then is set up the app settings so you remember that we created the mongodb settings model that we will use to store them the settings so now we actually need to put them in app settings so we're going to paste our mongod be settings in here like so then replace it with your own so it will look something like longer DB plus SRV your username your password and your cluster [Music] URL I will share a link in the description below which tells you how you can get your connection string from Atlas and then we're going to pass it the database name which in this case is car garage so do this for both app settings and app settings. Json as you can imagine I'm not going to put my connection string in here on video just because I don't want to give it away but I will um in a second off camera just go ahead and up update those settings so you'll I'll have same same as you so now that we've got that connection string and details in there we can go ahead and update our program file [Music] to have the have the DB context reference and start making use of it so we're going to add up here after the controllers we views we're going to add um a few lines of code which will just store those settings we talked about out so we're going to pop it in here so this is saying get the mongodb settings section from my app settings so this one um it will convert it to a mongodb settings model then configure it with that section so if you're not you know if you've done anything with ef core before or asp.net this is nothing new then we're going to add that context passing at the options but we're saying in our options rather than something like use SQL and said it's going to be used mongodb we pass it the atlas URI and we also pass it the database name and just with a little bit of you know null handling here and just like that we have our DB context set up with ef core ready to make use of in the next section where we'll be adding our services some people like to talk to their DB contact directly from the place they need it like the controllers but I prefer to have a separation so in this section we're going to create the services so we're going to have an interface for the car service and the booking service and then the implementation so just to clear things up we're going to go ahead and close all tabs then in the services folder we're going to add our interface so we're going to add a new item we're going to call it I car service Visual Studio will automatically know that it's an interface which is really helpful then we're going to copy all of this and we're going to paste it so this is just doing exactly as you expect we've just got a few methods that you now be available on the interface or we can get all cars we can get a car by its ID we can add a car edit a car or delete a car so you know the crud operations that you'd expect then we can go ahead and add that implementation so we're going to add a class we're going to call that unsurprisingly car service we're going to get back to implement iar service and now we can get Visual Studio to implement that interface so you'll notice it adds a methods in a different order to our interface but that's just because it defaults to alphabetical order so what we'll do is we'll start to implement those methods but before we do that we're going to add a couple of properties here well one property and the Constructor so we need access to our card DB context so that we can call it to make changes in our methods so we're going to create a local backing field here then we're going to have it passed in vir dependency injection and then we assign it so nice and simple then the first thing we're going to do is do add so we're going to say here in ad that we're going to do we're going to call the cardb context we're just going to say add that new car we're also going to do a couple of lines of code for the change tracking because this tutorial is shown that this also has the change tracking as part of EF core with this provider so we're just going to console it out just to show that it's happening of course if you're doing this in production you would probably use something like ilogger to actually save this change tracking officially but since this is just a quick sample we will just do it the old fashioned way with console. right line and we're just going to ask it to do the Long View because that just gives us some more information then after that the last thing we're going to do in this method is just to say save those changes great so that's add done next we're going to move on to delete so we're going to copy and paste some code here because it's it will look fairly similar so all we're saying here is because we actually are deleting a car that already exists we need to go in and say get that car for us then just check if it exists or not if it does exist then ask it to be removed and then the same lines again we were just asking it to detect the changes print out the debug View and save the changes we've also got a quick else here so if a car doesn't exist we just let let the application further up or the user know that the car can't be deleted next up is edit and that follows a very similar pattern to the delete we will um get the car but then in this case if the car isn't null first thing we do is we get the details from the updated car that got passed in and update the properties on that car then we update and again print out the change tracking and very similar error message down here next is get all cars so that's going to be a pretty simple one but with a couple of things your mail may not have seen before so we're going to do return C DB context cars we're going to do an order by because we want to get them back in the order they were added now something that you may or may not know is that the object ID field in M Mong b a documents is stored as a it looks like a goodd but under the hood as they're AO generated for you they're actually generated in a way that can be trapped chronologically so by ordering it by the ID we're actually getting it back in the order they were added which is perfectly optional I just like doing it then we're going to add a uh chain on a core here called asno tracking which comes from EF core because we know that we're just reading we don't want any changes we're specifically just saying don't worry about tracking here because we know that we're not doing anything it's one of those things that's just a good practice to do in in production so we're just adding it here just for good practice and then we're saying you know make it as as inumerable and then we get that list of cars back then finally for the C car by ID we're just going to paste something which is very similar but we're just saying yeah get the cars first all default with its ID nice so that is the car service done now we can move on to implementing the car booking service so just like with the car service we're going to create an interface and an implementation so the first thing we're going to do is add a new item we're going to call this I booking service unsurprisingly going to copy and P paste some information here so this is just the methods of you to declare it's all very similar to the car we've got the get all one get by by ID add edit and delete so now we can add the implementation so we can add a new item and this is going to be our booking service we can say that that's going to implement our booking service again implement the interface and the first thing we're going to do is we're going to just like with the car service we're going to get the book and context we're also going to do a Constructor that takes it in as a parameter and we're just going to assign it there we go so the first thing we're going to do then is Implement ad so we're going to say that the book card going copy and paste of the book car again just like with a car um is we're going to get the car so that we know the car that goes to the booking if the book car isn't null or is null sorry then we're going to throw an exception otherwise we're going to update our booking to say the associated car model is a model of the car update to say that it's booked and then the usual stuff for the F core where we're calling update because we want to update the book car to say hey the it booked now so we're going to make sure that it knows that the car has been updated to be booked then we're going to add the new booking then usually the tech changes print it out and save the changes so that is add the next we're going to do is uh Delete booking so we're going to copy that from here paste again so very similar to the cars we're going to um get the get the booked car because as you'll see later on we're going to up update it to say that it's not booked anymore say that the yep there you go the book C is not booked anymore get the booking if we find one then remove the booking but also update the card so it knows it's not booked anymore and then the usual with the error handling that we've seen before nice so next up will be edit so we will go ahead and do that and again as say all the code I'm copying and pasting comes to the written version of this tutorial which you can find as a link down below so we're going to do edit next and we're going to say that I'm going to copy and paste okay so like just like before nice and simple save that and then we're just going to do get booking so again that's going to be just like this car but for bookings instead so car debut context bookings do cars dot um um order by ID we'll do bookings to b b the ID as no tracking again and then as an inumerable cool and then this one is going to be as you'd expect that book in by ID cool so that's our services implemented but what we need to do now before we move on to the next stage is just to add these to dependency injection so we've you know we've we've added the interfaces and everything but we do actually need to tell dependency injection to make use of these so what we're going to do here is we're just going to say Builder doservices do add scoped so while it's in scope we're going to do it so I car service car service and then we'll do the same again for the booking service again this is just standard C nothing new cool so now we've done that we can go on to implementing our view models view models are technically optional but I just like to have decoupling in application and view models act as a messenger between the front end and the back end so in this instance we're going to be creating four view models a list view model and an ad view model for both cars and bookings and these will be used later on in our razor pages so the first thing we're going to do is add a new folder called view model so add new folder we call it view models then we're going to close all these other files just to keep things nice and neat we're going to add a new view model the first one we're going to add will be our car list view model and this is going to have one property which is going to be public ironable of type car cars we need to do the using statement there we go so that's list done next up we're going to add car add view models this is a view model that will be used when we add a car add vew model this one again is only going to have one method which is public car sorry method property public car we're going to make that optional car or optional nullable so yeah so in this instance because we're not getting a whole list it's not going to be an inumerable of cars we're going to have one simple property which is the car that we're going to add now we're just going to do the same again for both booking list and booking ad so booking list view moded again it's going to be a simple I numerable but instead of car it's booking and last but by no means least we're going to add booking ad V model that's so so that's all those done one the next thing we need to do is add this to view Imports so view Imports is kind of like a global um usings for your front end and so the reason we need to add this is that we want want to use it later on for the um front end so it will know when we're saying this is a model type that we're using in these front end Pages this is where it comes from so it's in views view Imports we just want to make sure that it's there so we want to do at using super card booking system. viw models and with that done we are done with the view models now that we have the backend completed including the services and the view models it's time to start using doing our front end and we're going to start off with the controllers and we're going to have two controllers one for car and one for booking so the first thing we're going to do is make one for cars so we're going to add a new controller here so we're going to do add controller it's going to give us a list of templates to choose from so in our case we want empty so we're going to call this one car controller not home controller one car [Music] controller first thing we're going to do then is add a reference to our car service so it's going to be read only I car service call it car service then we will go ahead and replace not replace add a Constructor what's un happy about oh I've done it in the wrong place silly me so move that into the correct place it should be inside the class not the name space so we've got a reference to our car service that we can start using so the front end talks to the service the service talks to the database so we've now got index so we're going to start updating the index to have to be the page that we visit so we're going to say here yeah so we're creting a new carless view model and we're saying that the cars property inside of that view model is going to be the result of getting all cars on the car service then return that view so we visit the page later on and it calls index it will then produce a list of all cars nice so next we're going to add some methods for the crud operation so in this case we've already done read by index so create update and delete we're going to have two methods for each one one is going to be an HTTP get and the other's going to be an HTT post so we don't need to add any attributes on top of this next method because um it defaults to get so we're just going to say public eye action result add and we're just going to say return view the reason we do this is because we're not going to be doing anything at this point we're just going to be moving to a new page that you'll see later on so we're just going to save that then we got to do the post this is a bit where once we've gone to a new page that we'll create later once we actually save it that will then call the Post version of this so I'm going to copy and paste some code but I will talk you what it's doing so we specified it's a post we then passing it that car r view model if the model state is valid so all the fields are correct and it's happy with the values then we'll create a new car with it with those details then just add that car and then return to index if it it's not valid then we'll just return the same view again with the car ride view model so basically if it doesn't work reload the same page so that they they have the opportunity to fix whatever's wrong with the with the page edit will be a bit more involved so again it's going to have a get a get and a post so we're going to start with get so we're going to take the ID and we're using string here because it's a data type the front end understands if the ID is null then will return not found otherwise we will um pass the ID as an object ID to our car service and return The View with that specific car and then we'll do the post version for edit so that's taking a car to be edited if it's valid then edit the car and go back to index otherwise return a bad request if something goes wrong outside of model State then add a model arrow that we will capture on the front end that says that it failed and then if you're not returning back to index because something went wrong but it's not a bad request then just return the view of the car a bit like with edit the edit um with the yeah with the previous edit um not edit ad see developer there we can't get our words mixed up but yes like with ADD if there's a problem return The View with the same object again so the user got an opportunity to fix it then finally we have delete so we have the get version which is very similar to the edit but the reason the reason that we have a separate page of delete you'll see later on it's just because we showed different information so the delete post is a bit more involved so we're checking that the car exists then we're trying to delete the car if the car was deleted successfully then we add uh a string to Temp data which is a way to share data between Pages then we just go back to index otherwise we um update the view data error message property with an error message and if that went wrong then we just carry on and say hey the selected car is this and then return that selected car so again they can make some changes so that's the car controller done now for the booking controller and the booking controller again will be very similar so we're going to add a controller we going do Another Empty one we're going to call it booking controller this time just like we saw with the service the booking controller cares about both the car and the booking service so we're going to add two local properties here one for the booking service and one for the car service service we're going to pop in a Constructor which takes some the heads injection the booking service and the car service assign them then just like with car in the index we're going to create a new view model get all the bookings and then return the view of those bookings we're going to do a get and post for ad so again these are very similar it's booking ad view model update the details with the the the car booking that you're trying to update add it via the service and go back to index we'll do the get and post for edit next these all look very similar to Car Service which is why I'm going through them quite quickly but if you do want to have a look at them in more detail you can of course look at the written tutorial so we've got the edit takes a string checks for it gets the booking updates it all pretty much the the same as the car controller just for bookings and then finally we can just pop in delete paste that here there we go so we'll race here again just delete do some checking and delete and go back to the index if it successfully deletes otherwise go back to the view and just add some information so just like that we have added our controllers and we now have something that our front end viewers will be able to talk to when they're looking using the convention of looking for the controllers with the names shared by the front end now we have the controllers in place we can start creating the views and VI razor pages that will talk to those controllers so we'll go ahead and again close all tabs just CU I like to keep things nice and organized then inew views we're going to create a new sa folder so obviously we're going to create a folder for car uh cars and bookings but for now we will do one for cars so we'll call the control view car okay that sub folder so we'll just this is typically if you've seen asp.net NBC before this is just a convention where views go into the the name of the view will be the folder it lives in so now we've created that folder we're going to add a new view so we're going to right click add a View and we're going to make sure that we pick razor view empty click add we're going to name keep this one as a default of index so if you remember we have an index in our controller so this index will reference that controller to know what to do so we want to add a placeholder for error handlings if you remember earlier on we did U stuff intm data for if there's an error so what we want to do is is add that in so the first thing we're going to do is add the one for car deleted this is actually a success so we're just going to say if if temp dat has got got information then just pop a a success and you'll see later on will just appear at the top then we're going to start to actually handle everything else so first of all if there's no no CS at all in the database then we want to say hey there's no results then what we're going to do is display the rest of the information so I'll explain what's going on here at the end but we're going to add a table so we've done the if so now we're doing an El so if there are cars create a table this is using bootstrap classes because this comes with s.net MVC out of the box so we can take advantage of it so we're creating our headers for our um properties that we've got on our bookings not bookings cars as well as an actions column then we're saying that for each car that we've got in our model so that's from our cars property on our car list view model we're going to do a um go through them and display a table uh a cell under that column for each bit of information then for the actions column we're going to add some buttons so we can go to edit for that car we can do delete for that car if the car isn't booked then we'll also add a button to allow them to book it and then that ends a table and then at the end we've got a button that just says add new car so if you want to add a new car rather than do anything with existing cars you've got that button there as well so we can go ahead and save that it just makes sense to have this as our index because we're having a you we want to have a list of cars as our homepage so we do need to just quickly make sure that in our program.cs we actually update it so that our default route goes to car so rather than home we're just going to say go to car but if we actually clicked on the buttons now nothing would happen in our index because they the views for them don't exist yet so the first thing we'll do is add a view for adding cars so we're going to do a new view again add and this one is going to be called ad going to specify the model so in this case the model is going to be our car ad view model we're going to do a H2 just to give it a bit of a title on the page this time rather than checking temp data we're going to check the view data for an error message so if there is one display that on the page and now we can go ahead and Implement a form so I'll paste it in here and then as usual I'll talk through it it so we're creating a post form for the car controller for ad so where we saw we had that get and post for each method endpoint the controller this is going to map to that so this is going to go to the Post endpoint for ad then it just does the validation then add the label so we can pop in the information about the cars that we want to save and a button to do it nice now we'd want to make sure that the the user can navigate back to the list of cars if they decide not to not to go back to it anymore so we're just going to add a quick button at the bottom here we could format it but it doesn't matter too much but yes just Klick a back to list button just in case it's SC of cancel already if we don't want anymore then do that so that's edit now we're going to add sorry now we're going to do edit so we're going to add a new view going to call this one ands surprisingly edit so we'll do that then we're going to add the model and the H2 in again so this time we've got a model of a car rather than a view model and we're going to say that we're updating the model from that model it's going to be another quick form with a button at the bottom so it's going to look very similar this time we're saying that it's it calls the edit endpoint we do some validation here we also have this input type hidden for ID here because we don't need to actually display the ID on the page but we do need to associate the ID with the form so that it knows what car we're editing because that's what will be passed to the edit method so we're again it's just some forms with some information in and a button at the bottom if you want to go back to the list of cars then we're going to do delete so we're going to add a view for delete going to add in the usual model H2 and checking for errors but we're going to do something slightly different here so instead of using a form we're going to be using um divs and um a different type of tag so DL so I think it's like data label tell no anyway yes so here what we're doing is it's not a form because we don't need anything to change this isn't an editable form for the user it's informational so we're displaying the model the number plate and the location so it's just to say you know this is the information about the car that you've chosen to delete then we will add add a form so this is just a form for confirming the deletion so again we've got this hidden value then we're saying saying delete and then unclick we're actually doing a clever little JavaScript script here so we'rendo: oh, você tem certeza de que deseja excluir o carro, então ele lhe enviará um bom pop-up para confirmar que eles realmente desejam excluí-lo e, em seguida, o padrão Go para a lista de carros para que possamos fechar todos eles de vez em quando podemos criar uma subpasta para a reserva C, então adicionaremos uma nova pasta que chamaremos de reserva e, em seguida, vamos adicionar arquivos muito semelhantes que Tínhamos antes, então, novamente, adicionaremos uma visualização e este para listando aqueles que vai ser chamado de índice vamos copiar o código que está bom parece muito semelhante, então estamos verificando se há informações de dados temporárias sem resultados e, em seguida, fazendo um cabeçalho e linhas para as informações mais ações, mas neste caso não tenhamos uma ação para uh agendamento porque já estamos em agendamentos então isso apenas exibe as agendamentos bom agora podemos adicionar então vamos adicionar uma visualização vamos chamar isso de novo, é praticamente a mesma coisa que temos a reserva, temos o se e um formulário apenas para receber o mas desta vez isto é Como temos uma data, onde temos a data de início e a data de término da reserva, eles são de data e hora, então acabamos de especificar aqui que esta é realmente uma data, então isso apenas personalizará o front-end para que você na verdade, tem seletores de data aqui em vez de apenas uma caixa de texto, o que apenas ajuda com um pouco de validação de dados e também é apenas uma experiência mais legal você tem menos probabilidade de obter formatação estranha porque é um tipo de data então você não precisa verificar para isso, mas também significa que você tem um seletor de datas que é melhor para o usuário então vamos editar para adicionar uma visualização isso será editado para adicionar tudo isso a edite outro formulário novamente oculto ID muitos deles são muito parecidos com esses exibições e o botão de confirmação verifica que você realmente deseja excluir a reserva e então tem o botão no de volta para Go para a lista então lá está, se você quiser ver o código completo para tudo isso, você pode para o Reaper que terá o Go Github link abaixo e, é claro, como mencionei alguns já se Go você quiser por este passo a passo e quiser o código para copiar e colar, também pode encontrar isso no tutorial escrito nos links abaixo, agora que temos isso é hora de testar nosso aplicação , então meu o aplicação está em execução, mas na verdade tem um erro porque cometi um erro então, se eu mover isso para aqui, você verá o que média, então tenho um erro de ouvir sobre qualquer um e pontos de Bônus para você se você notou o erro que cometi então o erro que cometi é que, no índice do carro, lembrei-me Go de adicionar o modelo de visualização Go da lista de carros como um modelo na parte superior, então se às visualizações abaixo do carro Go e para o índice no topo aqui, preciso adicionar modelo modelo de visualização da lista de carros, então se eu em frente e executar isso agora, descobriremos que ele funciona novamente agora, no meu caso, você verá quando funcionar anúncios que, como eu tenho a versão do tutorial escrito disso, na verdade, adicionei alguns dados fictícios ao banco de Go banco de dados uh para carros você verá alguns carros listados então o seu você não verá isso, mas verá o botão para adicionar um carro, então aqui estamos temos alguns carros que já existem temos os cabeçalhos que vimos AIT temos os cabeçalhos que vimos e os botões de ação e podemos adicionar um novo carro para, por exemplo , podermos adicione um carro novo aqui e 14 podemos fazer o VW. Veja o Polo um pouco diferente do seu número da placa. Se pudermos criar um local, apenas devolvemos o aeroporto de Man CU primeiro, adicione um carro e lá temos nosso carro existente, mas talvez tenhamos resolvido que queremos mudar o Go carro do aeroporto para o centro da cidade para que possamos clicar em editar, podemos -lo para que possamos fazê-lo ha semana para que possamos entrar e dizer oh,Go eu gostaria de reservá-lo, talvez eu queira reservá-lo de hoje até para que possamos reserva o carro,30então digitei fazer por meio do um para o componente seletor de datas, configuramos isso Go de modo que, se um agendamento for bem-sucedido, ele nos levará de volta à página de índice desse controlador a partir dessa instância de agendamento para que você possa ver aqui que temos nossa lista de agendamentos se se você quiser à nossa página inicial, podemos simplesmente Go excluir a reserva aqui e você pode ver aqui que ainda temos nossos três carros listados, mas agora o botão de reserva contra o pólo desaparece porque nós o reservamos poderíamos à reserva e Go poderíamos dizer que não é aquele, não se deixe esquecer a barra à reserva, poderíamos Go dizer que exclua a reserva no modelo da propriedade que a página 3 de confirmação aparece, podemos excluir a reserva e, em seguida, podemos à Go rota para a lista e você pode ver agora que o botão de reserva apareceu de volta para o Tela Mo del legal,3 nós também podemos em Go frente e uh editar carros nós poderíamos talvez um alterar outros detalhes além do local, mas também podemos excluí-los para que possamos Go em frente e exclua o pólo que acabamos de adicionar mas não queremos a fazer isso porque já temos uma reserva, então o que vamos fazer é excluir a captura de Runo, então vamos clicar em excluir uma página muito semelhante aparecerá, mas desta vez para o carro, em vez da reserva, exclua clique em excluir carro ele será excluído com sucesso, você receberá a mensagem na parte superior aqui e verá que ele não está mais na lista aplicação de etapa completa em funcionamento que aproveita os novos provedores do de Bo mongod que está atualmente em pré-visualização para dar uma olhada no roteiro disponível como um link na descrição abaixo onde você pode ver quais recursos estão por vir no plano para o novo codificação satisfeita do fornecedor

Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Vídeo
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
Exemplo de código

Salvando dados no Unity3D usando SQLite


Sep 07, 2022 | 13 min read
Tutorial

Manipulação de aggregation pipelines complexas com c# C#


Nov 15, 2024 | 5 min read
Início rápido

MongoDB e C Sharp: tutorial de operações CRUD


Sep 23, 2022 | 12 min read
Tutorial

Criando um jogo de captura de espaço no Unity que sincroniza com o Realm e o MongoDB Atlas


Jun 26, 2024 | 24 min read