{"id":112,"date":"2018-03-29T04:21:00","date_gmt":"2018-03-29T02:21:00","guid":{"rendered":"https:\/\/kindsonthegenius.com\/blog\/2018\/03\/29\/restful-web-services-tutorial-7-working-with-databases-insert-country-using-dbcontext\/"},"modified":"2020-11-05T14:25:01","modified_gmt":"2020-11-05T13:25:01","slug":"restful-web-services-tutorial-7-working-with-databases-insert-country-using-dbcontext","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/blog\/restful-web-services-tutorial-7-working-with-databases-insert-country-using-dbcontext\/","title":{"rendered":"RESTful Web Services Tutorial 7 &#8211; Working With Databases (Insert Country using DBContext)"},"content":{"rendered":"<p>Hello! Good to see you, I really appreciate your effort in learning. Thumbs up to you!\ud83d\ude03\ud83d\ude03\ud83d\ude03\ud83d\ude03<\/p>\n<p>In this tutorial, we are going to access the database we created in Tutorial 6 and Tutorial 7 with the help of Entity Framework. Entity Framework(EF) allows us to sync our\u00a0 .Net application with the database and make changes from the .Net code.<\/p>\n<div style=\"clear: both; text-align: center;\"><\/div>\n<p><b>We would cover the following in this tutorial<\/b><\/p>\n<ol>\n<li><a href=\"https:\/\/kindsonthegenius.com\/blog\/restful-web-services-tutorial-7-working-with-databases-insert-country-using-dbcontext#t1\">Review of Tutorial 5 and Tutorial 6<\/a><\/li>\n<li><a href=\"https:\/\/kindsonthegenius.com\/blog\/restful-web-services-tutorial-7-working-with-databases-insert-country-using-dbcontext#t3\">Examine the Changes to the Application Structure<\/a><\/li>\n<li><a href=\"https:\/\/kindsonthegenius.com\/blog\/restful-web-services-tutorial-7-working-with-databases-insert-country-using-dbcontext#t3\">Modify the Controller File<\/a><\/li>\n<li><a href=\"#t4\">Write a Post Method for Country<\/a><\/li>\n<li><a href=\"#t5\">Insert some Countries Using the POST Method<\/a><\/li>\n<li><a href=\"https:\/\/kindsonthegenius.com\/blog\/restful-web-services-tutorial-7-working-with-databases-insert-country-using-dbcontext#t6\">PUT Method<\/a><\/li>\n<li><a href=\"#t7\">DELETE Method<\/a><\/li>\n<li><a href=\"#t8\">Test all the Operations <\/a><\/li>\n<li><a href=\"#t9\">Next Steps<\/a><\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<h3 id=\"t1\">1. Review of Tutorial 5 and Tutorial 6<\/h3>\n<p>In Tutorial 5, we\u00a0 installed SQL Server and then used SQL Server Management Studio to create the Employees sample database we would use to store the employees data. We also created the relationships between the tables using database diagrams.<\/p>\n<p>In Tutorial 6, we went back to Visual Studio and created the Entity Data Model using Entity Framework. This makes is possible to automatically sync our .Net code with out database without having to write any stored procedure or any SQL queries.<\/p>\n<p>&nbsp;<\/p>\n<h3 id=\"t2\">2. Examine the Changes to the Application Structure<\/h3>\n<p>You need to understand what changes took place when you created the Entity Data Model<\/p>\n<p>In the Solution Explorer, find EmployeeDataModel.edmx<br \/>\n(The edmx file is a container for both the designer\/class diagrams and the models, the .cs files that hold the classes)<br \/>\nExpand this file to display the content. The folder structure is as shown in Figure 1<\/p>\n<p>&nbsp;<\/p>\n<div style=\"clear: both; text-align: center;\"><a style=\"margin-left: 1em; margin-right: 1em;\" href=\"https:\/\/2.bp.blogspot.com\/-Tlv3lnC84SE\/Wrw-2ZRXW8I\/AAAAAAAABqs\/mA0PAKUCCG4hhJ-xvx3Lmbur8sd5mOmEACLcBGAs\/s1600\/EntityDataModel%2BTutorial%2B5%2BFigure%2B1.jpg\"><img decoding=\"async\" loading=\"lazy\" class=\"\" src=\"https:\/\/2.bp.blogspot.com\/-Tlv3lnC84SE\/Wrw-2ZRXW8I\/AAAAAAAABqs\/mA0PAKUCCG4hhJ-xvx3Lmbur8sd5mOmEACLcBGAs\/s400\/EntityDataModel%2BTutorial%2B5%2BFigure%2B1.jpg\" width=\"428\" height=\"448\" border=\"0\" data-original-height=\"795\" data-original-width=\"760\" \/><\/a><\/div>\n<div style=\"clear: both; text-align: center;\">Figure 1: EntityDataModel.edmx<\/div>\n<p>&nbsp;<\/p>\n<p>Notice that the Models have been created automatically for<\/p>\n<ul>\n<li>Employee<\/li>\n<li>Country<\/li>\n<li>Address<\/li>\n<li>Department<\/li>\n<\/ul>\n<p>In Tutorial 3, we created the model file (Employee.cs) manually inside the Models folder, but in this case, the model files have been generated automatically from an existing database. This is known as Entity Framework &#8211; Database First.<\/p>\n<p>&nbsp;<\/p>\n<h3 id=\"t3\">3. Create the Controllers<\/h3>\n<p>Expand the Controller folder. Notice that we have already one controller file, the EmployeesController<br \/>\nYou now need to create the controllers for Country<br \/>\nRight-click on the Controllers folder and Choose Add &gt; Controller<br \/>\nChoose Web 2 API Controller Empty and shown in Figure 2<\/p>\n<p>&nbsp;<\/p>\n<div style=\"clear: both; text-align: center;\"><a style=\"margin-left: 1em; margin-right: 1em;\" href=\"https:\/\/4.bp.blogspot.com\/-WEahpbC9jfg\/WrxDLqD1FCI\/AAAAAAAABq8\/gYBm0POX9aYbFquAbgdE65AoZ2CZi6kxACLcBGAs\/s1600\/API%2BController%2B-%2BEmpty.jpg\"><img decoding=\"async\" loading=\"lazy\" class=\"\" src=\"https:\/\/4.bp.blogspot.com\/-WEahpbC9jfg\/WrxDLqD1FCI\/AAAAAAAABq8\/gYBm0POX9aYbFquAbgdE65AoZ2CZi6kxACLcBGAs\/s400\/API%2BController%2B-%2BEmpty.jpg\" width=\"501\" height=\"356\" border=\"0\" data-original-height=\"723\" data-original-width=\"1018\" \/>\u00a0<\/a><\/div>\n<div style=\"clear: both; text-align: center;\"><b>Figure 2:<\/b> Web 2 API Controller Empty<\/div>\n<p>&nbsp;<\/p>\n<p>Give it a name CountryController<br \/>\nClick Add. So the CountryController is added<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h3 id=\"t4\">4. Write a POST Method for Country<\/h3>\n<p>We would write a POST method that would insert a record into the database using the data from the body of the HTTP POST request.<br \/>\nOpen the Country Controller file you created<br \/>\nCopy and paste the code in Listing 7.1 inside the class<\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<pre style=\"line-height: 125%; margin: 0;\"><span style=\"color: #888888;\">\/\/METHOD TO ADD A NEW COUNTRY<\/span>\r\n<span style=\"color: #0000cc;\">[HttpPost]<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">public<\/span> IHttpActionResult <span style=\"color: #0066bb; font-weight: bold;\">AddCountry<\/span>([FromBody]Country country)\r\n{\r\n   <span style=\"color: #008800; font-weight: bold;\">using<\/span> (<span style=\"color: #333399; font-weight: bold;\">var<\/span> db = <span style=\"color: #008800; font-weight: bold;\">new<\/span> EmployeeDBEntities())\r\n   {\r\n      db.Countries.Add(<span style=\"color: #008800; font-weight: bold;\">new<\/span> Country() \r\n      {\r\n         Id = country.Id,\r\n         Name = country.Name,\r\n         Capital = country.Capital,\r\n         Code = country.Code,\r\n         Nationality = country.Nationality\r\n      }\r\n        );\r\n        db.SaveChanges();\r\n      }\r\n   <span style=\"color: #008800; font-weight: bold;\">return<\/span> <span style=\"color: #0066bb; font-weight: bold;\">Created<\/span>(Request.RequestUri, Request.Content);\r\n}<\/pre>\n<p><b>Listing 7.1<\/b>: POST Method for Country<\/p>\n<p>&nbsp;<\/p>\n<p>The code is quite simple. The EmployeeDBEntities is known as a database context and provides functionality to handle database operations like Add(), Remove(), Delete() and SaveChanges().<\/p>\n<p>In this case, we got a Country object from the body of the request. Then extracted the fields\u00a0 and used them to create a new Country which is given to the Add() method as parameter. The Add method runs some kind of insert query against the database.<br \/>\nThe SaveChanges() commits the query.<\/p>\n<p>Before we test this code, write a code to retreive a list of countries. This is given in Listing 7.2.<br \/>\nCopy and paste this code into the CountryController.<\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<pre style=\"line-height: 125%; margin: 0;\"><span style=\"color: #0000cc;\">[HttpGet]<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">public<\/span> IEnumerable&lt;Country&gt; getCountries()\r\n{\r\n   <span style=\"color: #333399; font-weight: bold;\">var<\/span> db = <span style=\"color: #008800; font-weight: bold;\">new<\/span> EmployeeDBEntities();\r\n   <span style=\"color: #008800; font-weight: bold;\">return<\/span> db.Countries;\r\n}<\/pre>\n<p><b>Listing 7.2:<\/b> Code to Get List of Countries<\/p>\n<p>&nbsp;<\/p>\n<p>So now you have the POST method to Add a new Country as well as a GET method to retrieve the list of countries<br \/>\nBuild the project and make sure it builds successfully.<\/p>\n<p>&nbsp;<\/p>\n<h3 id=\"t5\">5. Insert some Countries Using the POST Method<\/h3>\n<p>Run the program.<br \/>\nOpen Advanced REST Client<br \/>\nMake a POST request using the code in Listing 7.3 as the request body. You can see <a href=\"https:\/\/kindsonthegenius.com\/blog\/restful-web-services-tutorial-4-testing-the-rest-apis-using-advanced-rest-client\/\" target=\"_blank\" rel=\"noopener noreferrer\">how to make POST request with ARC in Tutorial 4<\/a>.<\/p>\n<p><b>POST Request url<\/b>:<span style=\"color: blue;\"> http:\/\/localhost:24675\/api\/Country\/getCountries<\/span><\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<pre style=\"line-height: 125%; margin: 0;\"><span style=\"background-color: #e3d2d2; color: #a61717;\">}<\/span>\r\n<span style=\"color: blue;\">\"Id\"<\/span><span style=\"background-color: #e3d2d2; color: #a61717;\">:<\/span> <span style=\"color: blue;\">1<\/span><span style=\"background-color: #e3d2d2; color: #a61717;\">,<\/span>\r\n<span style=\"color: blue;\">\"Code\"<\/span><span style=\"background-color: #e3d2d2; color: #a61717;\">:<\/span> <span style=\"color: blue;\">\"NGN\"<\/span><span style=\"background-color: #e3d2d2; color: #a61717;\">,<\/span>\r\n<span style=\"color: blue;\">\"Name\"<\/span><span style=\"background-color: #e3d2d2; color: #a61717;\">:<\/span> <span style=\"color: blue;\">\"Nigeria\"<\/span><span style=\"background-color: #e3d2d2; color: #a61717;\">,<\/span>\r\n<span style=\"color: blue;\">\"Capital\"<\/span><span style=\"background-color: #e3d2d2; color: #a61717;\">:<\/span> <span style=\"color: blue;\">\"Abuja\"<\/span><span style=\"background-color: #e3d2d2; color: #a61717;\">,<\/span>\r\n<span style=\"color: blue;\">\"Nationality\"<\/span><span style=\"background-color: #e3d2d2; color: #a61717;\">:<\/span> <span style=\"color: blue;\">\"Nigerian\"<\/span>\r\n<span style=\"background-color: #e3d2d2; color: #a61717;\">}<\/span><\/pre>\n<p>Listing 7.3: POST Request Body<\/p>\n<p>&nbsp;<\/p>\n<p>Change the data to insert two more Country records<br \/>\nMake a GET request to retrive a list of countries<\/p>\n<p><b>GET Request url<\/b>:<span style=\"color: blue;\"> http:\/\/localhost:24675\/api\/Country\/AddCountry <\/span><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h3 id=\"t6\">6. PUT Method to Update a Record<\/h3>\n<p>Listing 7.4 gives the PUT method to edit and update a country from the database.<br \/>\nCopy and paste this code in the CountryController file.<br \/>\nI have used lambda expression to select a country whose id corresponds to the id coming from the request body.<\/p>\n<p>The where clause in the lambda expression reads:<\/p>\n<p>&#8220;where s such that s.Id is equal to country.id&#8221;<\/p>\n<p>&nbsp;<\/p>\n<pre style=\"line-height: 125%; margin: 0;\"><span style=\"color: #888888;\">\/\/METHOD TO UPDATE A COUNTRY<\/span>\r\n<span style=\"color: #0000cc;\">[HttpPut]<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">public<\/span> IHttpActionResult <span style=\"color: #0066bb; font-weight: bold;\">EditCountry<\/span>([FromBody]Country country)\r\n{\r\n   <span style=\"color: #008800; font-weight: bold;\">using<\/span> (<span style=\"color: #333399; font-weight: bold;\">var<\/span> db = <span style=\"color: #008800; font-weight: bold;\">new<\/span> EmployeeDBEntities())\r\n   {\r\n       <span style=\"color: #333399; font-weight: bold;\">var<\/span> oldCountry = db.Countries\r\n       .Where(s =&gt; s.Id == country.Id)\r\n       .FirstOrDefault();\r\n       oldCountry.Name = country.Name;\r\n       oldCountry.Capital = country.Capital;\r\n       oldCountry.Code = country.Code;\r\n       oldCountry.Nationality = country.Nationality;\r\n\r\n       db.SaveChanges();\r\n   }\r\n<span style=\"color: #008800; font-weight: bold;\">   return<\/span> <span style=\"color: #0066bb; font-weight: bold;\">Ok<\/span>();\r\n}\r\n<\/pre>\n<p><b>Listing 7.4: <\/b>PUT Method to Update a Country<\/p>\n<p><b><br \/>\n<\/b><b><\/b><\/p>\n<h3 id=\"t7\">7. DELETE Method to Delete a Record<\/h3>\n<p>The DELETE method is given in Listing 7.5 to delete a record from the database.<br \/>\nCopy and paste this code in the CountryController file<\/p>\n<p>Notice the four lines needed to delete a record<\/p>\n<ul>\n<li>the Attach method attached the\u00a0 entity (coming from the request) to the database context<\/li>\n<li>the Remove method carries out the delete operation<\/li>\n<li>the next line updates the context<\/li>\n<li>the SaveChanges commits the delete operation<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<pre style=\"line-height: 125%; margin: 0;\"><span style=\"color: #888888;\">\/\/METHOD TO DELETE A COUNTRY<\/span>\r\n<span style=\"color: #0000cc;\">[HttpDelete]<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">public<\/span> IHttpActionResult <span style=\"color: #0066bb; font-weight: bold;\">DeleteCountry<\/span>([FromBody]Country country)\r\n{\r\n    <span style=\"color: #008800; font-weight: bold;\">using<\/span> (<span style=\"color: #333399; font-weight: bold;\">var<\/span> db = <span style=\"color: #008800; font-weight: bold;\">new<\/span> EmployeeDBEntities())\r\n    {\r\n        db.Countries.Attach(country);\r\n        db.Countries.Remove(country);\r\n        db.Entry(country).State = EntityState.Deleted;\r\n        db.SaveChanges();\r\n    }\r\n    <span style=\"color: #008800; font-weight: bold;\">return<\/span> <span style=\"color: #0066bb; font-weight: bold;\">Ok<\/span>();\r\n}<\/pre>\n<p><b>Listing 7.5:<\/b> DELETE Method to Delete a Country<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h3 id=\"t8\">8. Test all the CRUD Operations<\/h3>\n<p>At this point, you can carry out INSERT, SELECT, UPDATE and DELETE operation on the Countries database using the CountryController.<br \/>\nRun the program<br \/>\nUsing Advanced REST Client, insert some records\u00a0 into the database. Remember to change the Id for each new insert because the insert would fail if the Id is not unique<br \/>\nPerform some PUT and DELETE requests to make sure it works well<\/p>\n<p>If everything works fine, then congratulations! If you have some challenges, let me know in the comment box below.<\/p>\n<p>&nbsp;<\/p>\n<h3 id=\"t9\">9. Next Steps<\/h3>\n<p>We have successfully completed the REST API for manipulation the Countries information. Now, as a quiz, try to create controllers for the other three tables:<\/p>\n<ul>\n<li>Employees<\/li>\n<li>Departments<\/li>\n<li>Addresses<\/li>\n<\/ul>\n<p>If you did it correctly, fine. In the next lesson, Tutorial 8, I would give you the code for the other tables without giving much explanation. For now, try to do it yourself.<\/p>\n<p>I would like to thank you for learning!!<\/p>\n<p><a href=\"http:\/\/kindsonthegenius.blogspot.com\/#top\">\ud83d\udc46\ud83d\udc46\ud83d\udc46Top\ud83d\udc46\ud83d\udc46\ud83d\udc46<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello! Good to see you, I really appreciate your effort in learning. Thumbs up to you!\ud83d\ude03\ud83d\ude03\ud83d\ude03\ud83d\ude03 In this tutorial, we are going to access the &hellip; <\/p>\n","protected":false},"author":2,"featured_media":685,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[289],"tags":[],"_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/112"}],"collection":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/comments?post=112"}],"version-history":[{"count":8,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/112\/revisions"}],"predecessor-version":[{"id":1774,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/112\/revisions\/1774"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/media\/685"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/media?parent=112"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/categories?post=112"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/tags?post=112"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}