• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
info@dotnettec.com | +91-8800268750

DotNetTec

  • Home
  • Tutorials
    • Programming Language
      • C#
      • JavaScript
    • .Net Development
      • .NET Framework
      • ASP.NET Web Forms
      • MVC Architecture
      • Web API
      • .NET Core Framework
    • Front End Frameworks
      • JavaScript
      • HTML
    • Cloud Computing
      • Microsoft Azure
    • Database
      • SQL Server
    • Google Maps API
    • RPA
      • Blue Prism
      • UiPath
  • How to
  • Knowledge Base
  • Shop

Web API CRUD Operations using ASP.NET MVC and Entity Framework

February 13, 2020 by Ravi Kumar Leave a Comment

In this article, I will discuss asp.net web api crud operations and how to implement crud operations in web api using entity framework with C# example.

  • Keep reading on how to create Web API in ASP.NET C#, Interview Questions on ASP.NET WEB API

Web API CRUD Operations with Entity Framework

Here I am using the last project which I have created in the previous article on how to create asp.net web api. For the User class, we have properties like UserId, Name, Address, Contact.

public class User
    {
        public int UserId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Contact { get; set; }
    }

Now here I am going to use Entity Framework as an ORM tool so that we can perform the CRUD operations. Find the below steps and follow it:-

Step 1: First of all, for the above User model class, we have to define a database table name as User. So for using the entity framework make sure that you have installed the Entity Framework NuGet package.

install entity framework nuget package

Step 2: Now I have renamed the Models folder with the name Database and added one more class for the DatabaseContext. You need to inherit this class from DbContext which is a built-in class available in the using System.Data.Entity;

Step 3: Now define the constructor for database class and here we have called the base class constructor and in the base class constructor, we have to pass the database connection string.

Step 4: Add a User class by using the DbSet<User> and also define your connection string in the web.config file.

using System.Data.Entity;
using WebAPI.Data;

namespace WebAPI.Database
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext() : base("DefaultConnection")
        {

        }

        public DbSet<User> Users { get; set; }
    }
}
<connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="data source=localhost\SQLExpress; initial catalog=WebAPI_CRUD;persist security info=True;user id=sa;password=tiger; MultipleActiveResultSets=True; App=EntityFramework"/>
  </connectionStrings>

Step 5: As you know in this example, we are using Entity Framework Code First approach so we need to do the migration process to create a User table in the database by using the below commands :

migration-commands

  • enable-migrations
  • add-migration initial
    (The above commands will create a file with the name of initial inside the migration folder as shown below:)

initial migration file

  • update-database -verbose
    (This command will create the User table in the database as shown below:-)

database table

Now let see how to write the code to perform the CRUD operations on this User table. Find the below source code:-

crud operation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Data;
using WebAPI.Database;

namespace WebAPI.Controllers
{
    public class UserController : ApiController
    {
        DatabaseContext db = new DatabaseContext();

        //api/user
        public IEnumerable<User> GetUsers()
        {
            return db.Users.ToList();
        }

        //api/user/2
        public User GetUser(int id)
        {
            return db.Users.Find(id);
        }

        //api/user
        [HttpPost]
        public HttpResponseMessage AddUser(User model)
        {
            try
            {
                db.Users.Add(model);
                db.SaveChanges();
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Created);
                return response;
            }
            catch (Exception ex)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                return response;
            }
        }

        [HttpPut]
        public HttpResponseMessage UpdateUser(int id, User model)
        {
            try
            {
                if (id == model.UserId)
                {
                    db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    return response;
                }
                else
                {
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotModified);
                    return response;
                }
            }
            catch (Exception ex)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                return response;
            }
        }

        //api/user
        public HttpResponseMessage DeleteUser(int id)
        {
            User user = db.Users.Find(id);
            if (user != null)
            {
                db.Users.Remove(user);
                db.SaveChanges();
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                return response;
            }
            else
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
                return response;
            }
        }
    }
}

Download Source Code

Conclusion

I hope you liked this article on asp.net web api crud operations c# example. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Category iconASP.NET Web API,  How to Tag iconasp.net web api crud operations,  web api crud operations,  web api crud operations c# example,  web api crud operations with entity framework

Subscribe to our blog.

Get the latest posts delivered right to your inbox.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Recent Posts

  • Google Maps Draw Polygon Get Coordinates
  • Check if point inside polygon Google Maps JavaScript
  • How to Create a Calendar Control in ASP.NET
  • Interview Etiquette Before, During and After
  • How to Attend Telephonic Interview Tips

Products

  • Online Shopping ASP.NET Project Source Code Online Shopping ASP.NET Project Source Code
    Rated 5.00 out of 5
    $69.00 $39.00
  • eCommerce Website Source Code in ASP.NET eCommerce Website Source Code in ASP.NET $99.00
  • responsive-aspnet-mvc-grid-view ASP.NET MVC full Ajaxify and Bootstrap Grid with CRUD Operation
    Rated 4.67 out of 5
    $21.00 $9.00
  • Hospital Management System Project ASP.Net Source Code
    Rated 5.00 out of 5
    $99.00
  • Whatsapp Bulk Message Sender Source Code WhatsApp Bulk Message Sender Source Code
    Rated 5.00 out of 5
    $69.00

Footer

.NET Developers Blog

Learn .NET, Programming Languages, Web App Development, APIs Development & Integration, Google Maps JavaScript APIs, and Cloud Services, through the latest articles, step-by-step tutorials, code examples, live projects, interview ebooks, and best practices.

Sitemap

  • About
  • Blog
  • Shop
  • Contact
  • Privacy Policy

Expertise

  • Web Development
  • Custom Software Development
  • Web API Development
  • Google Maps APIs

Newsletter

Get the latest news, posts, and announcements straight to your inbox.

Copyright © 2021 DotNetTec.