net-core
  1. net-core-crud-operations

CRUD operations - ( ASP.NET Core & Entity Framework Core )

CRUD stands for Create, Read, Update, and Delete. These are the most commonly used operations in database management systems. This page will cover how to implement CRUD operations in an ASP.NET Core Web API using Entity Framework Core.

Syntax

The syntax for CRUD operations in Entity Framework Core is as follows:

Create

_dbContext.Add(entity);
_dbContext.SaveChanges();

Read

_dbContext.Entities.ToList(); // retrieve all entities
_dbContext.Entities.FirstOrDefault(e => e.Id == id); // retrieve entity by id

Update

_dbContext.Update(entity);
_dbContext.SaveChanges();

Delete

_dbContext.Remove(entity);
_dbContext.SaveChanges();

Example

Here's an example model class for a Product entity:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

To implement CRUD operations for this entity, first create a DbContext class and add a DbSet<Product> property:

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // configure entity properties
        modelBuilder.Entity<Product>()
            .HasKey(p => p.Id);
        modelBuilder.Entity<Product>()
            .Property(p => p.Name)
            .HasMaxLength(50)
            .IsRequired();
        modelBuilder.Entity<Product>()
            .Property(p => p.Price)
            .HasColumnType("decimal(18,2)")
            .IsRequired();
    }
}

Next, create CRUD operations in a controller:

[Route("api/products")]
public class ProductsController : ControllerBase
{
    private readonly MyDbContext _dbContext;

    public ProductsController(MyDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [HttpGet]
    public ActionResult<IEnumerable<Product>> List()
    {
        return _dbContext.Products.ToList();
    }

    [HttpGet("{id}")]
    public ActionResult<Product> Get(int id)
    {
        var product = _dbContext.Products.FirstOrDefault(p => p.Id == id);
        if (product == null)
        {
            return NotFound();
        }
        return product;
    }

    [HttpPost]
    public IActionResult Create(Product product)
    {
        _dbContext.Products.Add(product);
        _dbContext.SaveChanges();
        return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
    }

    [HttpPut("{id}")]
    public IActionResult Update(int id, Product product)
    {
        if (id != product.Id)
        {
            return BadRequest();
        }
        _dbContext.Update(product);
        _dbContext.SaveChanges();
        return NoContent();
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        var product = _dbContext.Products.FirstOrDefault(p => p.Id == id);
        if (product == null)
        {
            return NotFound();
        }
        _dbContext.Remove(product);
        _dbContext.SaveChanges();
        return NoContent();
    }
}

Explanation

ASP.NET Core uses Entity Framework Core to interact with the database. Entity Framework Core provides an ORM (Object-Relational Mapping) layer that allows you to map domain model objects to database tables, and perform CRUD operations through LINQ (Language Integrated Query).

In the example above, we create a DbContext class that represents a database session. We add a DbSet<Product> property to this class, which serves as an abstraction over the Products table in the database.

In the ProductsController, we inject the MyDbContext instance via the constructor. We then create actions corresponding to HTTP methods that perform CRUD operations on the Products table.

The List and Get actions retrieve one or more products from the database using LINQ queries. The Create action adds a new product to the database by adding it to the Products table and calling SaveChanges to persist the change. The Update action updates a product by first retrieving the existing product from the database and then calling SaveChanges to persist the change. Finally, the Delete action removes a product from the database by retrieving the existing product and calling SaveChanges to persist the change.

Use

CRUD operations are the foundation of most database-backed web applications. By implementing CRUD operations in an ASP.NET Core Web API using Entity Framework Core, you can easily create a RESTful API that interacts with a database.

Important Points

  • CRUD stands for Create, Read, Update, and Delete.
  • Entity Framework Core provides an ORM layer that allows you to map domain model objects to database tables, and perform CRUD operations through LINQ.
  • The DbContext class represents a database session and provides access to the database tables through DbSet<T> properties.
  • HTTP methods can be mapped to CRUD operations in an ASP.NET Core Web API using Entity Framework Core.

Summary

In this page, we covered how to implement CRUD operations in an ASP.NET Core Web API using Entity Framework Core. We discussed the syntax, example, explanation, use, important points, and summary of CRUD operations. By following the examples outlined above, you can easily create a RESTful API that interacts with a database.

Published on: