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.
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.
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 :

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

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

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

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; } } } }
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.
Leave a Reply