MongoDB Provider for EF Core – C# Tutorial

freeCodeCamp.org · Beginner ·🛠️ AI Tools & Apps ·1y ago

Key Takeaways

This video tutorial demonstrates how to use MongoDB with Entity Framework Core in C#, including setting up a development environment, data modeling, and building a restaurant reservation system using MongoDB Atlas sample data.

Full Transcript

hi everyone welcome to this tutorial on using mongodb with Entity framework core in C I'm Bo K and I'll be teaching this course I'll start by giving you a brief introduction to mongodb and an introduction to Microsoft's Entity framework core next I'll cover how to use the mongodb EF core provider after going through technical details with some basic examples we'll create a full project with mongodb and Entity framework core so you can see how everything works together the project will use mongodb Atlas sample data to create a restaurant reservation system mongodb is a popular nosql database designed to handle large volumes of data and provide high performance scalability and flexibility unlike traditional relational databases mongodb stores data in flexible Json like documents this document oriented approach allows for the storage of complex data structures in a more natural and intuitive way in mongodb data is stored in collections which are similar to tables in relational databases but without a fixed schema this means you can have documents with different structures in the same collection this flexibility is one of the key advantages of using mongod Tob especially when dealing with unstructured or semi-structured data let's take a look at an example of a mongodb document imagine we have a collection called users that stores information about users in an application here's what a typical document might look like in this document we have various Fields such as name email age and address the address field itself is an embedded document containing multiple subfields like Street city state and zip Additionally the Hobbies field is an array of strings while this looks like Json mongodb stores data in a binary format called bon or binary Json bson extends the Json model to provide additional data types such as integers floats dates and binary data this binary format is optimized for performance and flexibility allowing mongodb to efficiently store and retrieve data another important feature of mongodb is its ability to scale horizontally this means you can distribute your data across multiple servers making it easier to manage large data sets and Ensure High availability MDB also supports Rich queries indexing and aggregation making it a powerful tool for a wide range of applications for example you can perform a query to find all users who live in a specific city mongodb is widely used in various industries from e-commerce and content management to realtime analytics and Internet of Things applications its flexibility and scalability make it an excellent choice for modern applications that need to handle diverse and dynamic data now that we have a basic understanding of what mongodb is and why it's popular let's move on to another essential tool in our Tex stack Microsoft's Entity framework core Entity framework core often abbreviated as EF core is a modern object database mapper foret it allows developers to work with a database using net objects eliminating the need for most of the data access code that developers usually need to write EF core is a lightweight extensible and crossplatform version of the popular Entity framework data access technology it supports a variety of database engines including SQL Server SQL light and mongodb one of the main benefits of using EF core is that it enables developers to work with data in a more intuitive and objectoriented way instead of writing raw SQL query you can interact with your database using link the language integrated query and strongly typed classes let's take a look at a basic example imagine we have a product class here it is pretty simple with just three Fields using EF core you can create a context class that represents a session with the database and includes a DB set for each entity type you want to query or save this code defines a class named appdb context that inherits from entity framework cores DB context class this class is used to interact with the database inside this class there's a DB set product property called products which represents a collection of product entities and corresponds to a table named products in the database the onc configuring method is overwritten to configure the database connection specifying that SQL Server is the database provider but you can also use other databases besides s server the method uses an option Builder to set up the connection with a placeholder for the actual SQL server connection string this connection string obviously should be replaced with the real one containing the necessary details to connect to the database when you create an instance of appdb context in the application it uses this configuration to perform operations like quering or saving product entities in the products table with this setup you can perform crud uh create read update delete operations using EF core for example to add a new product to the database you can use this code this code demonstrates how to add a new product to the database using NTI framework core an instance of appdb context is created and within this context a new product object with the name laptop and price $999.99 is instantiated this new product is then added to the products collection managed by the appdb context finally the save changes method is called to save the changes to the database effectively inserting the new product into the products table to query products you can use Link this code also demonstrates how to query the database using Entity framework core an instance of app DB context is created and within this context a query is made to retrieve all products with the price greater than 500 the results are stored in a list called products then a loop iterates through each product in the list printing the name and price of each product to the console EF core takes care of translating these link queries into the appropriate SQL commands for your database this makes data access simpler and more maintainable EF core also supports Advanced features like change tracking lazy loading and migrations which help you manage database schema changes over time in summary EF core is a powerful omm that simplifies data access and net applications by allowing you to work with your data using net objects and Link its support for multiple database engines and its extensibility make it a versatile choice for a wide range of applications next we'll see how the mongodb EF core provider Bridges the gap between mongodb and EF core allowing us to use the familiar EF core patterns with a mongodb database The mongodb Entity framework core provider is a tool that enables developers to use mongodb with Entity framework core combining the flexibility of mongodb with the familiar API and design patterns of EF core this provider allows you to work with mongodb using the same code first and Link query methodologies that you would use with relational databases streamlining development and reducing the learning curve for those already familiar with ef core the mongodb EF core provider Bridges the gap between mongodb and EF core by supporting basic crud operations link queries and embedded documents among other features here are some key capabilities code first workflows you can Define your data models in C and use EF core to generate the mongodb schema rather than starting with the database schema and generating code from it this is particularly useful for developers who prefer to manage their database structure through code crud operations the provider supports basic create read update and delete operations for example you can add a new record to the database using the same code we saw earlier link query support you can use Link to perform queries against mongodb allowing you to leverage your existing knowledge of C sharp and.net to interact with the database change tracking e of course change tracking capabilities are supported enabling automatic detection and saving of changes made to your data entities embedded documents the provider supports embedded documents allowing you to store related data within a single document which is a common pattern in mongodb class mapping and serialization your C classes are mapped to mongodb collections with support for various data types and serialization settings to ensure that data is stored correctly now we'll go over a quick example on how to use the mongodb EF core provider and later we'll create a full project in Visual Studio code so you can see everything in context in this section we'll explore how to define data models and perform crud operations using the mongodb Entity framework core provider with mongodb Atlas this integration allows you to Leverage The flexibility of mongodb with the familiar patterns of EF core to get started you need to add the necessary new get packages to your project these packages allow your application to interact with mongodb through EF core using the same context and entity definitions you would use with a relational database before you can perform crud operations you need to set up a mongodb atlas cluster and connect your application to it here are the steps note that we'll be going over these in detail when we create the project soon first sign up for a MB Atlas account you can sign up for a free one at their website next create a new cluster mongodb Atlas provides a free tier that is perfect for development and smallscale applications then you get a connection string you can obtain your connection string from the mongodb atlas dashboard it will look something like this so after getting set up on MB Atlas time for the code you need to define a class using a model for your entity for this example we'll create a customer class this customer class represents the structure of the documents stored in the mongod DB collection to begin using Entity framework core create a context class that derived from DB context the DB context derived class instance represents a database session and is used to query and save instances of your entities the DB context class exposes DB set properties that specify the entities you can interact with while using that context this example creates an instance of a DB context derived class and specifies the customer object as a DB set property with the mongodb EF provider you can use a code first workflow this means you define your classes first and EF core will handle the creation and management of the underlying mongodb schema this is particularly useful for mongodb which does not enforce a schema allowing for flexible and dynamic data structures once we've created a DB context class we need to construct a DB context options Builder object and call its use mongodb method this method takes two parameters a manga client instance and the name of the database that stores the collections you are working with the used mongu DB method returns a DB context options object pass the options property of this object to the Constructor for your DB context class now let's see how to code the crud operations we'll just focus on each operation individually to create a new document in mang you use the ad method on the dbet and call Save changes here's an example of creating a new customer this code creates a new customer instance and adds it to the customer's collection the save changes method saves the new customer to the mongodb database to read documents from The mongodb Collection you can use Link queries on the DB set this is an example of retrieving all customers this code retrieves all customers from the customer collection and prints their details to update an existing document you retrieve the document modify its properties and call Save changes here's an example of updating a customer's order this code finds the customer named boars and updates their order to smartphone to delete a document you retrieve the document remove it from the DB set and call Save changes here's an example of deleting a customer this code finds the customer named Bo KS and deletes them from the customer collection EF core's change tracking capabilities are fully supported enabling efficient updates to documents when you modify an entity and call Save changes EF core will generate the necessary mongodb commands to update only the changed Fields by using the mongodb EF provider you can seamlessly integrate mongodb's flexible document model with ef core's robust om capabilities providing a powerful tool set foret developers to build modern applications now let's put everything together and develop a full restaurant reservation system from scratch so let's see how to use mongodb with ef core in a real world project well this is kind of like a demo project we're going to make a restaurant reservation system and we are going to use some sample restaurant data data that mongodb provides so before we create our project let's get our database set up so this is free we just have to sign in or sign up now if you're signing up for the first time it may make you set up a project as far as part of the sign up process or we can just go to new project and I'm going to call it rest res for restaurant reservations and then we'll just go through this process here of signing up and then I just need to create a cluster and I'm going to create a free cluster and I'll just set all this the rest of this to default you can also change the region to get a region that's closer to where you live and I will do create deployment and we have to make sure our IP address is added and so it's going to add it's going to automatically add your local IP address but if you're switching systems you may have to make sure your IP address is is Whit listed so you can connect from that IP address and then we need a database user and then I'll just create the database user and then we can choose a connection method now we're going to be coming back to this but we're going to need this this mongu DB uh URI but I'm going to copy that later so I'll just click done for now and I'm going to click add data and then the load load sample data so this is great for any projects that you're working on and when you're learning you don't need to find your own data somewhere you can start with a sample data set and that makes learning how to do things with mongodb a lot easier so we're just going to start with a sample data and so when we create the project there's already going to be a lot of data to work with we're specifically going to be using their restaurant database but they have a lot of other data you can work with and this actually has a bunch of so this has eight sample data sets so you can see them all here here's all the different sample data sets you can work with we will be using the sample restaurant data set but it's going to load all of them into the database so our database is still being set up in the background right now so let's get our project set up now there's a few different ways we can create a project some people may be using visual studio some people may be using visual studio code now since I'm running on Mac OS a visual studio they're I guess not they're deprecating Visual Studio on Mac OS and it's going to be mainly focused on windows so I'll be using visual studio code now Visual Studio Works more out of the box for C projects and asp.net project projects but Visual Studio code also works you just have to install the right extensions so if we go to the extensions you're going to make sure to install the C dev kit and when you install the C dev kit it's also going to install some other things like the C support and some other things and once you get this installed it's going to take a while to install but it's helpful to go through this walkth through it should appear right here on your welcome screen and then it's going to have a few things you have to do like connect your account set up your environment um I guess open your folder that's to open if you already have a folder you're going to use but we're going to actually create a new net project so now that we have the C devkit installed we can create our new project so I can either click this button or I can go to the command pet pallet you can use the shortcut key or go to view command pallet and then we just have to search foret new project it's already showing at the top for me because I've recently used that so I'll select new project and then it's going to give us some different templates we can use so for this example we're going to use the net core web app model view controller template and then we can uh name the new project I'm going to name it rest res so restaurant reservation and then press escape and then I'm am going to choose the default directory I already opened this Visual Studio code in a directory so it's going to save in that directory and then I will create the project okay so now you can see it's creating all these project files here now this is one good thing about asp.net core it's a very flexible web framework and it allows to scaffold out different types of web applications that have slight differences in terms of their UI and structure like I said we're using the MVC project and this is going to make use of static files and controllers but you could also do other things like react but MVC with the chtml files which we'll see later are the most commonly used now if you're not on vs code you'll be using visual studio and there's some different ways that you need to create your project or you can use the command line interface so if you go to the article that I have linked to in the description you can see the commands if you want to use the net CLI to create the project and now that we have this project created we want to go ahead and add the required new git packages depending on whether you're on Visual Studio or Visual Studio code the way to use the package manager is a little different but let's see how to do on Visual Studio code so just go to view command pallet or you can use the shortcut and then we're going to go to newg get add newg get package you can type it in but I've already recently used this so it's at the top and then we can just search for for the package we need so we actually just have to add one new get package and then it has all the rest of them as dependencies that are already installed automatically so we'll do mongod db. entity and if I just search for that it should come up see the mongodb Entity framework core so I'm just going to select that package and I will install the latest package version and then that's all there is to it so what going to automatically install the Microsoft EF core package and the mongodb C driver as a dependency okay now we can create the models before we can start implementing the new packages we just added we need to create the models that represent the entities we want in our restaurant reservation system that will of course be stored in mongodb Atlas as documents so we're going to create models for the restaurant reservation and mongodb settings so let's start with the restaurant model this is going to represent the restaurants that are available to be reserved in our system so let's go into the models directory here and I'll just do new file and then I'm going to do restaurant. CS now if you're using visual studio there'll be a you can just go to new model and and then type in the name but for visual studio code we have to make a new file just like that so I'm just going to paste in some code here and you can see we are going to be using mongod db. IND framework core like the we just installed and these are just the fields that will be in our database for each uh object the ID name Cuisine and burrow now you can see the collection attribute right here before the class this tells the application what collection inside the database we are using this allows us to have different names or capitalization between our class and our collection should we want to now so we can kind of understand this fully let's actually go and look at the collection on our database so our data set was successfully loaded we did that earlier so let's browse the collection we we're actually going to look at the the data in here so we can see all the different sample databases but we're only going to be using the sample restaurants database specifically this restaurants collection so we can see all the different items and you can see each item in this collection is going to have an address a burrow Cuisine grades name restaurant ID we're simplifying this and we're only going to be using the burrow the cuisine and the name so if we go back here that's why we have um the cuisine burrow name and then the object ID because every object in mongodb has its own object ID if you're designing something from scrap and you don't already have some sample data you can basically put in anything you want here but I just took some fields from the database we already have so let me save that and we also need to make a reservation class to represent any reservations we we have in our system so I'm going to go to new file again you go to new class if you're on visual studio and this will be called reservation. Cs and I'm just going to paste in some code again here and so we're going to have the ID and then we're going to connect it to our restaurant by having a field for the restaurant ID that corresponds to our restaurant ID and we're going to bring in the restaurant name and the new thing we're going to have is a date and and the date is going to include the date and the time of the reservation that's why we are using a date time piece of data so we're going to just create one more called mongod DB settings. CS now this won't be a document in our database but we need a model class to store our mongodb related settings so they can be used across our application so I'm just going to paste and code again here and we can see we just have two we have the atlas URI this is what we saw when we were setting up mongod be uh Atlas earlier and we're going to have to bring in that information over here later and then we have our database name which in this case is restaurants now we'll be setting this data again later like I said so now we're about to set up EF core enry Entity framework core this is the ex in part we're going to start to implement EF core and take advantage of the new mongodb provider if you're used to working with ef core already some of this will be familiar with familiar to you so let's create a folder called Services now this this part can actually be anywhere but we're going to put it in the services folder and then I'm going to create a file called restaurant re reservation DB context so if you're used to EF core this will look familiar this class extends the DB context and we create uh dbet properties that store the models that will be present in the database and basically whenever you're using EF core you're going to have to do this part we also are going to over override the on model creating method you may notice that unlike when using SQL Server we don't call the two table we could call the two collection instead but this isn't required here as we specify the collection using attributes on the classes which I already showed you when we created the class and just go over this a little more uh in detail we first have Imports and we're going to import the models that we created that that are going to be used in here then we have the Nam space that is going to define the name space for the class grouping it with other related classes and avoiding naming conflicts then we have the class definition and this impairs from DB context making it a context class for EF core it will manage entity sets and coordinate database operations then we have the DBC set properties you always need these in EF core and this first one just represents the restaurant table in the database EF core will use this to perform crud operations on the restaurants entities and same for the reservations then we have this Constructor here this accepts DB context options and passes it to the base DB context Constructor this allows EF core to configure the context specifying the database provider and the connection string that's basically the other the other model we created and then finally uh we are going to overwrite the on model creating method this method is used to customize the model building process in this case is calling the base method and then registering the restaurant and reservation entities with the model builder this step is important for setting up the model configuration such as relationships constraints and mappings so we can see right here we're not calling the two table method that's what we would have to do if we were using SQL Server we could call the two collection instead but this isn't required here is we specify the collection using attributes on the classes this is where we specifi The Collection right here so there's a few different places that you can specify the collection let's just save all these and get these close so earlier we created the mang Tob settings model now we need to add the values that the property is M to mapped to in our app settings so if I go over here to app settings. Json we can add these new properties here and this obviously has to be updated so we need to get the correct URI so let's go back over here go to database connect and then I can just copy this URI right from here and now I just paste this in and then we'll just have to update our password and then we're going to add it to the settings. development. Json as well and I'll make sure to change this or delete this before it goes live so I don't have to blur out this URI in the video so now that we've configured our models and DB context it's time to add them to our program.cs file so go to program.cs and we can see the file here so after this line the builder. services. add controllers with view so we start with a configuration where we have this line that's going to retrieve the mongodb setting section from the applications config configuration file and then here is going to map the retrieved section to an instance of the mang settings class the mango settings class should contain properties that match the configuration file the atlas URI and the database name and as we know the MB settings class contains the properties that match the configuration file the ls Ur and the database name this line registers the M be settings configuration instance with the dependency injection container allows other services to access these through dependency injection then we have this line which registers the restaurant reservation DB request with the di container it makes the DB context available for dependency injection throughout the application and then we have the following section which configures the DB context to use the mongodb provider the mongodb method is past the atlas URI and the database name from the mang settings instance and uh if it's null an M an empty string will be used instead and now since I'm using all these things you can see the red squiggly lines we're going to have to add some using statements to import the appropriate things our models that we created the services and then of course ENT Entity framework core okay so I can save that I saved all the other files and now we're going to create the services it's time to create the services we we can use to talk to the database via the restaurant booking DB context we created so for each service we'll create an interface and a class that in implements it the first interface and service we'll Implement is for carrying out the crud operations on the restaurant's collection this is known as the repository pattern you may see people interact with the DB context Direct but most people use this pattern which is why we're going to do it in this tutorial so uh we have the we already created the services directory and now I'm going to create a new file this is going to be the I restant service. CS this is going to be an interface that's why I search with the letter I so I'll just paste in this code we have the import and then we have the namespace to group it with other related classes and interfaces and then we actually uh Define the interface so this an interface in C defines a contract that other classes must Implement so we're going to later create another class that has to implement the get all restaurants get restaurants by ID add restaurant edit restaurant and delete restaurant and so we're going to use this right now by creating a new file this is going to be the restaurant service so I got pasted in this code so we have Imports the the name space and then we are going to implement the interface that we just created and here we have this local restaurant reservation DB context object and a Constructor that gets an instance of the DB context via dependency injection then we have the add restaurant method which adds a new restaurant to the DB context and saves the changes and also it's going to uh print the state of the changes tractor to the console now in production you probably wouldn't use that you would use a different method but it's fine for this and then we have the delete restaurants obviously going to delete a restaurant so you can see it's looking for the restaurant that has the ID that's put in the first one that finds and then if it and then if it's not n it finds a restaurant then it's going to move it or remove it and it's going to save the changes here or there's going to be a an exception and then edit restaurant is pretty much similar um we're going to pass in the the new restaurant that's supposed to be updating we're going to find the restaurant that's be updated and then we're going to put the new name Cuisine and burrow to the rest restaurant that we have to update we going to update it and then we are going to detect changes and then we're going to write those changes and then save changes now we're going to get all restaurants and by the way we've been using the ID the ID field in our document is a special M be object ID type it's autogenerated when a new document is created uh what's useful about the ID property is that it can actually be used to Order documents because of how it's generated under the hood so we can order by descending so it's going to start the bottom go up or you can order by the the top the reason why I put order by descending is because one thing we're not going to implement in this is pagination so that's something that you can Implement later on your own if you want but when we actually see the application you'll see that it's going to list just the so we have take 20 there's a bunch of restaurants in the database we're only going to show 20 of them and we're going to order by descending so we're going to order uh basically display the last 20 documents added and the reason why we're going to do that is so you can easily see any new documents that we added so we could also just do instead of order by descending we could do order by and it'll take the the first 20 or if you don't have take 20 it'll show all of them but that takes a long time to load now if you haven't seen it before this asno tracking that method is part of EF core and and prevents EF tracking changes you make to an object this is useful for reads when you know no changes are going to ur occur okay so now we just have get restaurant by ID that's pretty self-explanatory we're going to get the first restaurant that has ID that was passed in okay I'm going to save this and then I better save this file so now that we're done with that we're going to create the reservation service so I am going to first make the interface so a new file IR reservation service. Cs and this is going to be pretty similar so this is the interface that we have to implement so let's do reservation service and this is basically the same as before but now we're doing it with the reservation so we can add a reservation and this time we just need to get the name from the restaurant that we're adding the reservation for and we already have the ID that we're going to pull in and when you we're going to delete the reservation remove the reservation to delete um edit the reservation it's all basically the same but now we're just editing the date that's really the only item that you can edit for the reservation and for the reservations we're also just just going to display the the 20 reservations but we're going to orderer by the beginning instead of the end of the list of reservations and then we can get the reservation by ID so let me save those we'll make sure to add them to the dependency injection so let's go back to the program.cs file actually let's close a lot of these files here's program.cs and add two more lines where we're going to add the services the restaurant service and the reservation service with the interfaces now we can create the view models before we implement the front end we need to add the view models that will act as a messenger between our front and back ends where required even though our application is quite simple implementing The View model is still good practice as it helps decouple the pieces of the app so first we're going to create the restaurant list view model this will be used as the model in our razor page later on for listing the restaurants in our database so first I'm going to create a new folder called view models and then in here we'll create a new file called restaurant list viw model. CS okay we'll paste in some code here and this is pretty simple cuz all this is doing is listing the restaurants and these are all going to be pretty simple so we're going to create a new view model uh restaurant ad view model and again I'll just paste in the code again now it's just a single restaurant instead of all the restaurants and then we have to do the same for the reservations so reservation list view model again this will be listing all the reservations and then we have the reservation ad view model which is just showing a single reservation okay make sure all these are saved now we have to add to the view Imports later on we'll be adding references to our models and view models and the views in order for the application to know what they are we need to add references to them in the view the undor view imports. CS HTML file inside the views folder so let me just show you where that F that folder is let's go to the Views folder and we have theore view imports. cshtml so there are already some references in there you can see but we're just going to really only have to make sure we add one line so we have the models we just need to know that we have the view models so I'll save that time to create the controllers now that we have the backend implementation and the view models we will refer to we can start working toward the the front end we'll be creating two controllers one for restaurant and one for reservation so we'll start with the restaurant controller so let's go to the controller folder here and we're going to create a new file this is just going to be called restaurant and if you're using visual studio you can use the MVC controller empty controller template so we start by importing everything such as the models the services The View models and then we have the name space and now we have this class definition since it's inheriting from controller this makes it an MVC controller then we're going to uh declare a private readon field for the restaurant service and now we have the Constructor that takes an IR restaurant service and assigns it to the private fieldcore restaurant service this index action this is an action method that retrieves all restaurants and returns them to The View using a restaurant list view model and then we have the add actions so this is a get action method that Returns the add restaurant View and this is a post action this next section is a post action that adds a new restaurant if the model state is valid otherwise it returns The View with the current model so you can see it's is just getting all the information to add the restaurant now we have the edit action here this first one is just a get action method just like before that Returns the edit restaurant view for a specific restaurant by its ID or it will return a 404 not found and then we have the the post action which is how you make the update it's going to update will update a restaurant if the model stays valid or if there's an exception it will add airor to the model State and return The View with the new method and similar with the delete we have the get request that is just going to return a delete restaurant view for a specific restaurant ID or we can do the get post request and so for this post request here it's going to delete it will see if the ID is is we'll see if the ID exists and then if so we're going to try to delete the restaurant and then we would redirect to the index page or we would catch the error and then if we haven't already redirected somewhere we're going to view the selected restaurant now the reservation one is pretty similar we won't go into it with as much detail but we do need to make a reservation. CS file and like I said it's similar to the restaurant controller but it has a reference to both the restaurant and the reservation Service as we need to associate the the reservation with the restaurant this is because at the moment the EF core provider doesn't support relationships between entities so we have to relate entities in a different way it's going to be very similar to the restaurant controller so I'm not going to go into detail we just have the reservation service and the rest service because we have to get the restaurant uh information in addition to the reservation information so everything else is very similar including all the airor messages we're to the Views section now that we have the backend and the controllers prepped with the endpoints for our restaurant reservation system it's time to implement the views so model view controller we have the model controller now it's the views this will be using razor Pages you'll also see a reference to classes from bootstrap as this is the CSS framework that comes with MVC applications out of the box we'll be providing views for the crud operations for both listings and bookings so first we're going to create a listings view now I'm going to open up here I'm going to go to the Views folder and I'm going to create a subfolder called restaurant and in here we're going to provide a view that will map to the root of SL restaurant which will be which will be by convention which will by convention look at the index method we implemented asp.net core MVC uses a convention pattern where you name the CSH HTML file the name of the inpoint or method it uses and it lives inside a folder named after its controller so that's why we created the restaurant controller here and inside the restaurant fold we're going to create a new file called index. cshtml now if you're using a template in Visual Studio you can use the razor view empty template but here I'm just going to add some code to the index file so we're going to specify which list view we're going to use and then right here this is a placeholder for the air handling if there is an issue deleting a restaurant we added a string to Temp data so we want to add that into the view if there's data to display and next we are going to handle if there are no restaurants in the database by displaying a message to the user and then the easiest way to display the list of restaurants and the relevant information is to use a table so we're just creating a table that has these headings named Cuisine BR actions and you can see we're getting this in so for each restaurant in the restaurants that we get we're going to list the name the cuisine the burough and then we have these different buttons edit button the delete button and the reservation button and then finally we have a button to add a new restaurant now it makes sense to have a list of restaurants as their homepage so before we move on let's update the default route from home to/ restaurant so I'm I'm going to go to the program.cs file and then if I go down here it right now we're using the home controller but I'm going to change this to restaurant if we ran this now the buttons would lead to 404s because we haven't implemented we haven't implemented them yet so let's do that we're going to implement the the buttons the edit the delete and the add buttons so to add a restaurant do a new file and add. cshtml and I'm actually going to make that a little smaller here and this is going to be pretty self-explanatory the title and then the aor message and then we are just going to create a form with different sections so we have an input field for the name for the cuisine for the burrow and then a submit button and then we just have a button to get back to the list so so that will go back to the list of restaurants now I need a view for editing this is almost identical to add but it uses the restaurant as a model as it will use the restaurant it's pasted to prepopulate the form for editing so we have the actual the model name here so you can see it's very similar to the add one so so now we just want to make a delete so new file delete. cshtml now instead of a form like the other one this is just going to be uh listing the information you can see the model name the cuisine the burrow and then it will do a form to delete a restaurant and I'll say are you sure you want to delete this restaurant and then if you do you click delete and will'll perform the delete action so let's save that and now we're going to add views for the reservations so let me go to new folder and do reservation and we're going to start with index and this is very similar to before with the table so I'm not going to explain it all but we will now do an add. cshtml and this is is also similar the only thing that's kind of to note is in the form we're using a datetime local type which will allow a drop down for both the date and the time and we're going to set the value to the current time and the current date and time and then the person can change it to when they want to make the reservation and when we special specify the format with just hours and minutes that means it's not going to have someone put in the seconds or milliseconds we're just going to have someone put the hours in minutes okay so now we'll do the edit one and then the only thing to note in edit is that um so we're the title is saying we're editing the reservation for this restaurant name for this time and you can see whenever we use the information for the date and time so the date and time are both stored in the date field and we always we going to put two local time and here we you calling the two local time method if we don't do that the time will not display as expected so so finally we will add delete and everything is pretty straight forward for this we are going to put all the information again using two local time for the time time and then we have the the delete form at the bottom here okay now we're basically done I'm just going to add one more thing which is optional to make it easier to navigate I'm just going to add links in the Navar to both our reservation page and our restaurant page so what I'm going to go I'm going to go to the Views folder and then shared and then I'm going to open up the layout file that HTML and then I'll scroll down here and I'm just going to update this is what right now there's just going to be a home and a privacy button I'm going to paste it and so there's going to be a restaurants and reservations button and it's going to use the restaurant controller reservation controller so now we can actually just run this so I'll go to terminal new terminal and then I can go into my directory and do net run now I just take this URL here okay and here's our page now it says no results I would expect there to already be results of the restaurants since we're connected to the database so that means we're doing something wrong here let's see what it is okay here's the problem in our app settings we have the database called restaurants but but if we go to the actual database on Atlas we can see it's called sample restaurants so this is supposed to be sample restaurants and then we also have to change this one okay let me just run this again okay now we can see all the restaurants now some the restaurants in the database don't have names that's why you see the blank thing and then we can see the Cuisines are all other in some ways would be cooler if we show we start the restaurants from the top instead of the bottom which is actually pretty easy to change we're going to go back to this I just want to show you this really quick which is in the restaurant service and oh that's reservation restaurant service if we do order bu like that and then I just restart this and then you can see we have all these different Cuisines all these different Burrows and all the names of the restaurants but we're going to go back to how it is how it was because of wanting to be able to see our new restaurants that we add so we can edit delete and Reserve like let's delete these ones that have no names if they don't have names why do we even have them in here so delete this one okay so let's add a new restaurant let's see if that works if we scroll down to the bottom add new restaurant and we'll say B pizza and then Cuisine pizza and then all the so for this database it's all New York so basically I guess that's not even a buau but you can put anything oh they're all New York buus I I didn't I don't think I mentioned that before but now we have our own restaurant including we can see all these other restaurants and also I can do a reservation so right now it's going to set the current time where I'm at but I can set the reservation for the 29th and we'll do 6 o'l and then I can reserve a table okay now it's showing the these are all our booked restaurants so we have a restaurant booked um at BO pizza for this time and we can book another restaurant so let's here Indian Oven we'll just do it for here okay so now we have two booked restaurants if we want to switch that we can so like maybe I want to change change the date so let's change this to the 30th update reservation so we've updated the reservation and if we go to restaurants we can also edit a restaurant maybe I want to edit the name so maybe instead of Indian Oven we'll change this to Indian stove and Cuisine I'm guessing it's Indian and then we can update the restaurant and then we can continue to delete Reserve see all the res restaurants the reservations so it works and if you want to make the application even better on your own you can make it so when you change a restaurant name it also changes the name of that restaurant and all the reservations however as it is now when you create the reservation it saves the what the name was when you create the reservation but we can go into the database and we can see how it is updated in the database so let me go to sample restaurants I'll go to the restaurants here and then I will search for name Indian stove and if I do the search we should see right here so the name has been updated in the database on mongodb ataly our application is complete now let's look at some Advanced features of mongodb Atlas since we already have access to the client when creating the DB context this allows us to perform Advanced mongodb operations such as Atlas search and Vector search these features enhance your application capabilities by enabling powerful search functionalities while still leveraging The Familiar EF core framework Atlas search is a full teex search engine provided by mongodb Atlas it allows you to run sophisticated search queries on your mongodb data with Atlas search you can Implement features like autocomplete faceted search and relevance-based sorting to use Atlas search with ef core provider uh follow these steps so you set up indexes in Mong Atlas go to your mongod Atlas cluster navigate to the search Tab and create a new index on your collection then Define the fields you want to make searchable next Define searchable fields in your models and you in your sear models ensure that the fields you want to search are properly defined this is an example of the the definition of a product model performing search queries use the m.net dri's capabilities to perform text searches since EF core itself does not directly support the mongodb specific search syntax you'll need to use the driver in conjunction with ef core this is an example this example shows how to perform a text search on the products collection the text filter helps search across all indexed Fields defined in your Atlas search index Vector search in mongodb is used for searching documents based on Vector similarities which is particularly useful for applications involving machine learning recommendations and natural language processing Vector search allows you to query documents using vectors representing text images or other high-dimensional data while the mongodb EF core provider simplifies crud operations some advanc features like Atlas search and Vector search require direct use of the mongod be.net driver however you can still integrate these operations within your EF core based application by using the driver for search functionalities and EF core for other data management tasks by combining EF core and mongodb's advanced features you can build powerful and flexible applications that Leverage The Best of Both Worlds structured data access patterns of EF core and the powerful search capabilities of mongodb Atlas in this course we've explored how to integrate MB with Entity framework core we covered the basic concepts and how to put everything together into a full proj

Original Description

Learn how to use MongoDB with EF Core in C#. After going though technical details with some basic examples, you will learn to create a full project with MongoB and Entity Framework Core. The project will use MongoDB Atlas sample data to create a restaurant reservation system. Sign up for MongoDB Atlas: https://www.mongodb.com/cloud/atlas/register?utm_campaign=freecodecamp_ef&utm_source=freecodecamp&utm_medium=referral Get code from the article: https://www.freecodecamp.org/news/using-entity-framework-core-with-mongodb EF Core Documentation: https://www.mongodb.com/docs/entity-framework/current/ Course developed by Beau Carnes. 🏗️ MongoDB provided a grant to make this course possible. Explore MongoDB further with free MongoDB University courses, Certifications, and Developer Center. 🔗 MongoDB University: https://learn.mongodb.com/?utm_campaign=freecodecamp_ef&utm_source=freecodecamp&utm_medium=referral 🔗 Certification: https://learn.mongodb.com/pages/certification-program?utm_campaign=freecodecamp_ef&utm_source=freecodecamp&utm_medium=referral 🔗 Developer Center: https://www.mongodb.com/developer/?utm_campaign=freecodecamp_ef&utm_source=freecodecamp&utm_medium=referral ⭐️ Contents ⭐️ ⌨️ (00:00) Course Introduction ⌨️ (00:37) Intro to MongoDB ⌨️ (03:15) Intor to Entity Framework Core ⌨️ (07:24) How the MongoDB EF Core Provider Works ⌨️ (09:34) Data Modeling and CRUD Operations ⌨️ (14:29) Atlas Search and Vector Search ⌨️ (17:16) Tutorial - Set up MongoDB Atlas ⌨️ (20:09) Tutorial - Set up Dev Environment ⌨️ (25:33) Tutorial - Building Reservation System ⌨️ (56:47) Tutorial - Testing Project 🎉 Thanks to our Champion and Sponsor supporters: 👾 davthecoder 👾 jedi-or-sith 👾 南宮千影 👾 Agustín Kussrow 👾 Nattira Maneerat 👾 Heather Wcislo 👾 Serhiy Kalinets 👾 Justin Hual 👾 Otis Morgan 👾 Oscar Rahnama -- Learn to code for free and get a developer job: https://www.freecodecamp.org Read hundreds of articles on programming: https://freecodecamp.org/news ❤️
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from freeCodeCamp.org · freeCodeCamp.org · 0 of 60

← Previous Next →
1 React: Production Server Setup Part 2 - Live Coding with Jesse
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
2 cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
3 Browser history tutorial - Beau teaches JavaScript
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
4 Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
5 React: Parameterized Routing with Next.js - Live Coding with Jesse
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
6 React: Dealing with jQuery Issues - Live Coding with Jesse
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
7 setInterval and setTimeout: timing events - Beau teaches JavaScript
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
8 Browser and Device Testing - Live Coding with Jesse
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
9 Last Minute Updates - Live Coding with Jesse
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
10 Post Launch Updates - Live Coding with Jesse
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
11 React: Setting Up Google Analytics - Live Coding with Jesse
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
12 React: Masonry Layout - Live Coding with Jesse
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
13 Load Balancing Digital Ocean Droplets - Live Coding with Jesse
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
14 try, catch, finally, throw - error handling in JavaScript
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
15 Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
16 Graphs: breadth-first search - Beau teaches JavaScript
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
17 React: Masonry Layout Part 2 - Live Coding with Jesse
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
18 React: WordPress API Live Search - Live Coding with Jesse
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
19 Creating WordPress Custom Post Types - Live Coding With Jesse
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
20 Dates - Beau teaches JavaScript
Dates - Beau teaches JavaScript
freeCodeCamp.org
21 Miscellaneous Front End Updates - Live Coding with Jesse
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
22 Merging a Pull Request from GitHub - Live Coding with Jesse
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
23 React + Prettier + Standard JS - Live Coding with Jesse
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
24 React: Sortable Responsive Table - Live Coding with Jesse
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
25 Geolocation Sorting by Distance - Live Coding with Jesse
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
26 Tradeoff Matrix - Agile Software Development
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
27 The Definition of Ready - Agile Software Development
The Definition of Ready - Agile Software Development
freeCodeCamp.org
28 Getting first React job without experience - Ask Preethi
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
29 React: Google Analytics Click Tracking - Live Coding with Jesse
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
30 Submitting a PR to an Open Source Project - Live Coding with Jesse
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
31 Should I go back to school to get CS degree? - Ask Preethi
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
32 Hero Section CSS Changes - Live Coding with Jesse
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
33 Working Agreement - Agile Software Development
Working Agreement - Agile Software Development
freeCodeCamp.org
34 A day at Pennybox with Co-Founder Reji Eapen
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
35 React: Sorting and Filtering Data - Live Coding with Jesse
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
36 React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
37 React: Building a New UI - Live Coding with Jesse
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
38 Definition of Done - Agile Software Development
Definition of Done - Agile Software Development
freeCodeCamp.org
39 Getting started with jQuery (tutorial) - Beau teaches JavaScript
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
40 Making a React Blog with WordPress Content - Live Coding with Jesse
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
41 React, NextJS, CSS - Live Coding with Jesse
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
42 jQuery events - Beau teaches JavaScript
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
43 React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
44 React: Working with API Data - Live Coding with Jesse
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
45 React: Refactoring Components - Live Streaming with Jesse
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
46 jQuery effects - Beau teaches JavaScript
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
47 More React Refactoring - Live Coding with Jesse
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
48 animate in jQuery - Beau teaches JavaScript
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
49 "Finishing" My React Site - Live Coding with Jesse
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
50 Starting a New React Project (P2D1) - Live Coding with Jesse
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
51 React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
52 The Agile Manifesto - Agile Software Development
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
53 jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
54 React Project 2 Day 3 - Live Coding with Jesse
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
55 The INVEST approach to product backlog items
The INVEST approach to product backlog items
freeCodeCamp.org
56 React Project 2 Day 4 - Live Coding with Jesse
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
57 Chickens and Pigs - Agile Software Development
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
58 React Project 2 Day 5 - Live Coding with Jesse
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
59 jQuery: add and remove DOM elements - Beau teaches JavaScript
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
60 React Project 2 Day 6 - Live Coding with Jesse
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org

This video tutorial teaches how to use MongoDB with Entity Framework Core in C# to build a restaurant reservation system. It covers setting up a development environment, data modeling, and implementing CRUD operations. By the end of the tutorial, viewers will have a working application using MongoDB Atlas sample data.

Key Takeaways
  1. Set up a MongoDB Atlas account
  2. Install the MongoDB EF Core provider
  3. Configure the development environment
  4. Create a new C# project using EF Core
  5. Define data models using Entity Framework Core
  6. Implement CRUD operations
  7. Build a restaurant reservation system using MongoDB Atlas sample data
  8. Test the application
💡 The MongoDB EF Core provider allows developers to use Entity Framework Core with MongoDB, enabling them to leverage the power of NoSQL databases in their C# applications.

Related Reads

📰
AI Tools that Actually Pay You Back: A Developer's Guide to Monetizing AI
Learn how to monetize AI tools as a developer and generate revenue streams
Dev.to AI
📰
How to Summarize PDFs Programmatically in 2026 (+ a Free No-Code Option)
Learn to summarize PDFs programmatically using AI tools and a free no-code option, saving time and effort
Dev.to · Ai tools overview
📰
The new ChatGPT macOS app redesign has made basic navigation so much worse
Learn how to adapt to the new ChatGPT macOS app redesign and optimize your workflow despite the changes to navigation
Reddit r/artificial
📰
Three Token-2022 Mints in One Week: Fees, Yield, and Soulbound
Learn how to build three different Token-2022 mints on Solana devnet in one week, including fee-bearing, interest-accruing, and soulbound tokens
Dev.to · atharv shukla
Up next
Huawei Ascend 910C Explained in 50 Seconds | China's Powerful New AI Chip 🇨🇳🤖
Learn with Fatimah Gondal
Watch →