Asp.net Core WebApi Core Webapi through Linq.

Mushahid AbbasiMushahid Abbasi
3 min read

Create a crud through linq in asp.net core web api

Creating a CRUD (Create, Read, Update, Delete) application using LINQ in ASP.NET Core Web API involves a straightforward process where you interact with a database using Entity Framework Core (EF Core). Here’s a step-by-step guide to achieving this:

1. Set Up the Project

Start by creating an ASP.NET Core Web API project if you haven't already.

2. Install Entity Framework Core

Ensure you have EF Core installed:

bashCopy codedotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

3. Create the Database Context and Model

Let's assume we're working with a Product model.

Model Class

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

DbContext Class

csharpCopy codepublic class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }

    public DbSet<Product> Products { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>().ToTable("Products");
    }
}

4. Configure the Database Connection

In your appsettings.json, define your connection string:

jsonCopy code{
  "ConnectionStrings": {
    "DefaultConnection": "Server=your_server_name;Database=your_db_name;Trusted_Connection=True;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

5. Register DbContext in Program.cs

Configure the dependency injection for your DbContext:

csharpCopy codevar builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseAuthorization();

app.MapControllers();

app.Run();

6. Create the CRUD Operations Using LINQ

Create Operation (POST)

csharpCopy code[HttpPost]
public async Task<IActionResult> Create(Product product)
{
    _context.Products.Add(product);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}

Read Operation (GET)

csharpCopy code[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id)
{
    var product = await _context.Products.FindAsync(id);

    if (product == null)
    {
        return NotFound();
    }

    return Ok(product);
}

[HttpGet]
public async Task<IActionResult> GetAll()
{
    var products = await _context.Products.ToListAsync();
    return Ok(products);
}

Update Operation (PUT)

csharpCopy code[HttpPut("{id}")]
public async Task<IActionResult> Update(int id, Product product)
{
    if (id != product.Id)
    {
        return BadRequest();
    }

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

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!ProductExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return NoContent();
}

private bool ProductExists(int id)
{
    return _context.Products.Any(e => e.Id == id);
}

Delete Operation (DELETE)

csharpCopy code[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
    var product = await _context.Products.FindAsync(id);
    if (product == null)
    {
        return NotFound();
    }

    _context.Products.Remove(product);
    await _context.SaveChangesAsync();

    return NoContent();
}

7. Create the Controller

Put everything together in a ProductsController:

csharpCopy code[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly MyDbContext _context;

    public ProductsController(MyDbContext context)
    {
        _context = context;
    }

    [HttpPost]
    public async Task<IActionResult> Create(Product product)
    {
        _context.Products.Add(product);
        await _context.SaveChangesAsync();
        return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(int id)
    {
        var product = await _context.Products.FindAsync(id);

        if (product == null)
        {
            return NotFound();
        }

        return Ok(product);
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var products = await _context.Products.ToListAsync();
        return Ok(products);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(int id, Product product)
    {
        if (id != product.Id)
        {
            return BadRequest();
        }

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

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ProductExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        var product = await _context.Products.FindAsync(id);
        if (product == null)
        {
            return NotFound();
        }

        _context.Products.Remove(product);
        await _context.SaveChangesAsync();

        return NoContent();
    }

    private bool ProductExists(int id)
    {
        return _context.Products.Any(e => e.Id == id);
    }
}

8. Test the API

You can test your API using tools like Postman or Swagger (which can be set up using the Swashbuckle.AspNetCore package).

Summary

This guide shows you how to implement a basic CRUD API in ASP.NET Core Web API using LINQ with Entity Framework Core. The ProductsController demonstrates how to handle standard CRUD operations with minimal boilerplate code, leveraging the power of LINQ and EF Core for database interactions.

0
Subscribe to my newsletter

Read articles from Mushahid Abbasi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mushahid Abbasi
Mushahid Abbasi