.NET Core Web API CRUD with Entity Framework | DotNetSchool

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET Web API Implementing CRUD with Entity Framework

ASP.NET Web API Implementing CRUD with Entity Framework: A Detailed Guide

1. Setting Up the Project

Step 1: Create a New ASP.NET Web API Project

  • Open Visual Studio.
  • Select "File" > "New" > "Project".
  • Choose "ASP.NET Web Application (.NET Framework)".
  • Provide a name for your project and click "Create".
  • In the "New ASP.NET Web Application" dialog, select "Web API" and click "Create".

Step 2: Install Entity Framework

  • Open the Nuget Package Manager Console and run the following command:

    Install-Package EntityFramework
    

2. Defining the Data Model

Entity Framework allows for code-first, model-first, and database-first approaches. For simplicity, we'll use the code-first approach.

Step 1: Define Entities

Let's create a simple Product entity.

public class Product
{
    [Key]
    public int ProductID { get; set; }
    [Required]
    public string ProductName { get; set; }
    public string Category { get; set; }
    [Required]
    public decimal Price { get; set; }
}

Step 2: Create the Database Context

Next, create a DbContext class that represents a session with the database and allows you to query and save instances of your entities.

public class ProductContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    public ProductContext() : base("DefaultConnection")
    {
    }
}

Step 3: Configure Connection String

Update the connectionStrings section in Web.config with your SQL Server connection details.

<connectionStrings>
  <add name="DefaultConnection" 
       connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-productcontext.mdf;Integrated Security=True" 
       providerName="System.Data.SqlClient" />
</connectionStrings>

3. Creating the Web API Controller

Step 1: Create Product Controller

Add a new Web API Controller to your project.

  • Right-click on the "Controllers" folder in Solution Explorer.
  • Select "Add" > "Controller".
  • Choose "Web API 2 Controller - Empty" and click "Add".
  • Name your controller, e.g., ProductController.

Step 2: Implement CRUD Operations

Below is an example of how to implement CRUD operations in the ProductController using Entity Framework.

public class ProductController : ApiController
{
    private ProductContext db = new ProductContext();

    // GET: api/Product
    public IEnumerable<Product> GetProducts()
    {
        return db.Products.ToList();
    }

    // GET: api/Product/5
    public IHttpActionResult GetProduct(int id)
    {
        Product product = db.Products.Find(id);
        if (product == null)
        {
            return NotFound();
        }

        return Ok(product);
    }

    // POST: api/Product
    public IHttpActionResult PostProduct(Product product)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Products.Add(product);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = product.ProductID }, product);
    }

    // PUT: api/Product/5
    public IHttpActionResult PutProduct(int id, Product product)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != product.ProductID)
        {
            return BadRequest();
        }

        db.Entry(product).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ProductExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // DELETE: api/Product/5
    public IHttpActionResult DeleteProduct(int id)
    {
        Product product = db.Products.Find(id);
        if (product == null)
        {
            return NotFound();
        }

        db.Products.Remove(product);
        db.SaveChanges();

        return Ok(product);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool ProductExists(int id)
    {
        return db.Products.Count(e => e.ProductID == id) > 0;
    }
}

4. Testing the API

You can test the API using tools like Postman or Swagger:

  • Postman: Send HTTP requests to your endpoints (GET, POST, PUT, DELETE) and verify the responses.
  • Swagger: Ensure your project is set up with Swagger for easier API testing and documentation. You can install the Swagger package via Nuget:
Install-Package Swashbuckle

After installation, configure Swagger in your WebApiConfig class located in the App_Start folder.

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    // Swagger configuration
    config.EnableSwagger(c =>
    {
        c.SingleApiVersion("v1", "Web API with Entity Framework");
    })
    .EnableSwaggerUi();
}

Conclusion

ASP.NET Web API paired with Entity Framework offers a flexible and powerful way to manage data-driven applications. This guide covered setting up the project, defining data models, creating the Web API controller, and testing the API. These steps form the foundation for building more complex and feature-rich applications.

Key Points Recap:

  1. Setup: Create an ASP.NET Web API project and install Entity Framework.
  2. Model Definition: Define entities (e.g., Product) and create a DbContext class.
  3. Controller Creation: Implement CRUD operations in a Web API controller.
  4. Testing: Use tools like Postman or Swagger to test and document your API.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET Web API Implementing CRUD with Entity Framework

Complete Examples, Step by Step: Implementing CRUD with ASP.NET Web API and Entity Framework for Beginners


Prerequisites:

  1. Visual Studio 2019 or later.
  2. Basic knowledge of C#.
  3. .NET Framework or .NET Core SDK.
  4. Basic knowledge of SQL Server (or another database you prefer).

Step 1: Create a New ASP.NET Web API Project

  1. Open Visual Studio and select Create a new project.
  2. Choose ASP.NET Core Web Application and click Next.
  3. Provide your project with a name, location, and solution name, then click Create.
  4. In the next dialog, select the API template. Ensure the framework version is set to .NET 6.0 (Long Term Support) or the latest version, then click Create.

Step 2: Set Up the Database Context with Entity Framework Core

  1. Install Entity Framework Core NuGet Package:

    • Right-click on your project in the Solution Explorer and choose Manage NuGet Packages.
    • Go to the Browse tab and search for the following packages:
      • Microsoft.EntityFrameworkCore.SqlServer
      • Microsoft.EntityFrameworkCore.Tools
    • Install them by clicking Install.
  2. Create a Model Class:

    • Right-click on the Models folder and choose Add > New Item.

    • Select Class and name it Employee.cs.

    • Implement the Employee class:

      namespace WebApiCRUD.Models
      {
          public class Employee
          {
              public int Id { get; set; }
              public string Name { get; set; }
              public string Email { get; set; }
              public string Department { get; set; }
          }
      }
      
  3. Create a Database Context Class:

    • Right-click on the Models folder and choose Add > New Item.

    • Select Class and name it AppDbContext.cs.

    • Implement the AppDbContext class:

      using Microsoft.EntityFrameworkCore;
      
      namespace WebApiCRUD.Models
      {
          public class AppDbContext : DbContext
          {
              public AppDbContext(DbContextOptions<AppDbContext> options) 
                  : base(options)
              {
              }
      
              public DbSet<Employee> Employees { get; set; }
          }
      }
      
  4. Configure the Connection String in appsettings.json:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=WebApiCRUD;Trusted_Connection=True;MultipleActiveResultSets=true"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    
  5. Configure Services in Program.cs:

    using Microsoft.EntityFrameworkCore;
    using WebApiCRUD.Models;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllers();
    
    builder.Services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    app.UseHttpsRedirection();
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();
    
  6. Run the Migrations to Create the Database and Tables:

    • Open the Package Manager Console in Visual Studio.

    • Execute the following commands:

      Add-Migration InitialCreate
      Update-Database
      

    This will create the database and a Employees table based on your model.


Step 3: Create the Controller to Handle CRUD Operations

  1. Add a New Controller:

    • Right-click on the Controllers folder and choose Add > Controller.
    • Select API Controller with read/write actions and click Add.
    • Name your controller EmployeesController.
  2. Implement the CRUD Operations:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using WebApiCRUD.Models;
    
    namespace WebApiCRUD.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class EmployeesController : ControllerBase
        {
            private readonly AppDbContext _context;
    
            public EmployeesController(AppDbContext context)
            {
                _context = context;
            }
    
            // GET: api/Employees
            [HttpGet]
            public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees()
            {
                return await _context.Employees.ToListAsync();
            }
    
            // GET: api/Employees/5
            [HttpGet("{id}")]
            public async Task<ActionResult<Employee>> GetEmployee(int id)
            {
                var employee = await _context.Employees.FindAsync(id);
    
                if (employee == null)
                {
                    return NotFound();
                }
    
                return employee;
            }
    
            // PUT: api/Employees/5
            [HttpPut("{id}")]
            public async Task<IActionResult> PutEmployee(int id, Employee employee)
            {
                if (id != employee.Id)
                {
                    return BadRequest();
                }
    
                _context.Entry(employee).State = EntityState.Modified;
    
                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmployeeExists(id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return NoContent();
            }
    
            // POST: api/Employees
            [HttpPost]
            public async Task<ActionResult<Employee>> PostEmployee(Employee employee)
            {
                _context.Employees.Add(employee);
                await _context.SaveChangesAsync();
    
                return CreatedAtAction("GetEmployee", new { id = employee.Id }, employee);
            }
    
            // DELETE: api/Employees/5
            [HttpDelete("{id}")]
            public async Task<IActionResult> DeleteEmployee(int id)
            {
                var employee = await _context.Employees.FindAsync(id);
                if (employee == null)
                {
                    return NotFound();
                }
    
                _context.Employees.Remove(employee);
                await _context.SaveChangesAsync();
    
                return NoContent();
            }
    
            private bool EmployeeExists(int id)
            {
                return _context.Employees.Any(e => e.Id == id);
            }
        }
    }
    

Step 4: Test the API

  1. Run the Project:

    • Press F5 or click the Run button in Visual Studio.
  2. Test with a Web Browser or a Tool like Postman:

    • Open a web browser or Postman.

    • Navigate to GET https://localhost:<port>/api/Employees to retrieve the list of employees.

    • Use POST https://localhost:<port>/api/Employees to add a new employee with a JSON body:

      {
        "name": "John Doe",
        "email": "john@example.com",
        "department": "IT"
      }
      
    • Similarly, you can test PUT and DELETE methods to update and delete employees.


Conclusion

Top 10 Interview Questions & Answers on ASP.NET Web API Implementing CRUD with Entity Framework

1. What is ASP.NET Web API?

Answer: ASP.NET Web API is a framework developed by Microsoft that allows developers to build RESTful web services easily. These services can support various clients including browsers, devices and mobile apps. Web API provides a streamlined platform for building APIs that are HTTP-based.

2. What is Entity Framework (EF)?

Answer: Entity Framework is an Object-Relational Mapper (ORM) for the .NET Framework that facilitates database operations using C# or VB.NET code. It allows for creating database tables from pre-defined classes, mapping database rows to instances of these classes, and managing transactions efficiently.

3. How do you set up a database context in Entity Framework?

Answer: To set up a database context, first install Entity Framework via NuGet Package Manager. Then, create a class that inherits from DbContext. Inside this class, define DbSet<T> properties for each entity you wish to manage, where T is the type of your entity. Example:

public class MyDbContext : DbContext
{
    public DbSet<Entity> Entities { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Configuration here
    }
}

4. How can you add a new entity using the Web API and Entity Framework?

Answer: In your Web API controller, include a method to insert a new entity. This involves taking a POST request, deserializing it into an entity, adding it to the DbSet, and calling SaveChanges() to commit the changes in the database. Example:

[HttpPost]
public IHttpActionResult AddEntity(Entity input)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    _db.Entities.Add(input);
    _db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = input.Id }, input);
}

5. What is the standard way to retrieve all entities in ASP.NET Web API with Entity Framework?

Answer: Fetching all entities typically uses the HTTP GET method without a parameter for the entity ID. From the controller, simply return the complete list of items from the DbSet. Example:

[HttpGet]
public IEnumerable<Entity> GetEntities()
{
    return _db.Entities.ToList();
}

6. How do you retrieve a specific entity based on its ID?

Answer: For retrieving a specific entity based on its ID, use a GET method with a route that includes an ID parameter. Utilize Find(), FirstOrDefault() or SingleOrDefault() methods of the DbSet to locate the entity. Example:

[HttpGet]
public IHttpActionResult GetEntityById(int id)
{
    var entity = _db.Entities.Find(id);
    if (entity == null)
        return NotFound();

    return Ok(entity);
}

7. Can you explain how to update an entity using ASP.NET Web API and Entity Framework?

Answer: Update an entity through a PUT or PATCH method in the controller. First retrieve the entity by ID, then modify its fields as needed and call SaveChanges() to commit. Example (for PUT):

[HttpPut]
public IHttpActionResult UpdateEntity(int id, Entity input)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var entity = _db.Entities.Find(id);
    if (entity == null)
        return NotFound();

    entity.Property1 = input.Property1;
    entity.Property2 = input.Property2;
    // Update other properties as needed

    _db.Entry(entity).State = EntityState.Modified;
    _db.SaveChanges();

    return StatusCode(HttpStatusCode.NoContent);
}

8. How do you delete an entity using ASP.NET Web API and Entity Framework?

Answer: Delete an entity by using a DELETE method in the controller and passing the ID of the entity to be removed. Retrieve the entity, remove it from the DbSet, and call SaveChanges(). Example:

[HttpDelete]
public IHttpActionResult DeleteEntity(int id)
{
    var entity = _db.Entities.Find(id);
    if (entity == null)
        return NotFound();

    _db.Entities.Remove(entity);
    _db.SaveChanges();

    return StatusCode(HttpStatusCode.NoContent);
}

9. What is eager loading in Entity Framework and why is it important?

Answer: Eager loading is a technique to load related data while querying the main entity. It prevents multiple separate queries being generated when accessing related data later. This is achieved using the Include() method. Example:

public IEnumerable<Entity> GetEntitiesWithRelatedData()
{
    return _db.Entities.Include(e => e.RelatedEntity).ToList();
}

Without eager loading, accessing e.RelatedEntity later might result in an additional database query (N+1 SELECT problem).

10. What best practices should be considered when implementing CRUD with ASP.NET Web API and Entity Framework?

Answer:

  • Exception Handling: Use try-catch blocks to manage and log exceptions.
  • Validation: Validate both the entity and the API models before processing.
  • Async/Await: Utilize asynchronous methods to avoid blocking threads (GetEntitiesAsync(), FindAsync(), etc.).
  • Unit Testing: Write unit tests for your Web API methods to ensure they behave as expected.
  • Resource Management: Ensure that any resources like DbContext are properly disposed of after usage.
  • Logging: Implement a logging strategy to record successful and failed operations.
  • Security: Protect against SQL injection attacks by using parameters and not concatenating strings.
  • Caching: Leverage caching mechanisms wherever possible to reduce database pressure.
  • Pagination: For large lists of data, consider implementing pagination to improve response time and manage memory usage effectively.

You May Like This Related .NET Topic

Login to post a comment.