Tuesday, August 13, 2019

Creating a POST (Insert) method in Asp.Net Core API Controller

In the previous post we created an API Controller and created a GET method, in this post we will create a POST method which will use Entity Framework Core to insert values to the database. We will use the same country controller and add a Create method.

Open the CountryController and add the following Create method, the method will take an object of type Country and insert the same to the Database.


        public void Create(Country country)
        {
            var _context = new UserRegistrationContext();
            _context.Country.Add(country);
            _context.SaveChanges();
        }

Build and run the project, we will use Postman to invoke the Create method. Since this is a POST method we cannot access this from the browser since we need to pass parameters, in this case we will have to pass a Country object to the POST method.





Once the POST method executes, we can execute the Get method to makes sure that the new value got inserted to the DB, the result of the GET method will be as follows. Notice that the new country France which we added is now listed in the GET method.




Search Flipkart Products:
Flipkart.com

No comments: