Building a CRUD Application with .NET Core and EF Core

9 June 2017

In this post, we will build a simple CRUD (Create, Read, Update, Delete) application using .NET Core and Entity Framework Core (EF Core). The goal is to create a Web API that connects to a database and allows basic data operations. We’ll go through the necessary steps, including setting up the project, configuring EF Core, and writing the code for each CRUD operation.

1. Setting Up the Project

To start, create a new .NET Core Web API project. You can use the dotnet CLI or Visual Studio. If you prefer using the CLI, navigate to your project folder and run the following command:

dotnet new webapi -n CrudApp

This will create a new Web API project called CrudApp.

2. Installing Entity Framework Core

Next, you’ll need to install the EF Core NuGet package for your project. Open the terminal and navigate to the project folder, then install the necessary EF Core packages for SQL Server (or another database provider if you prefer):

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Additionally, you need to install the EF Core tools to manage migrations and interact with your database:

dotnet add package Microsoft.EntityFrameworkCore.Tools

3. Creating the Model and DbContext

Now, let’s define the model and the DbContext for the application. We’ll create a simple model called Product with three properties: Id, Name, and Price.

Product Model

Create a new class file called Product.cs in the Models folder (you can create the folder if it doesn’t exist).

namespace CrudApp.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

DbContext

Next, create the ApplicationDbContext class in the Data folder, which will represent the connection to the database and include a DbSet property for the Product model.

using Microsoft.EntityFrameworkCore;
using CrudApp.Models;

namespace CrudApp.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options) { }

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

4. Configuring the Database Connection

Now, you need to configure the database connection in the Startup.cs file. This will connect your application to the database. In the ConfigureServices method, add the following code to configure the ApplicationDbContext:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddControllers();
}

You also need to add the connection string to the appsettings.json file:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=CrudAppDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

This connection string tells the application to use the SQL Server LocalDB instance. You can modify the connection string for other databases if needed.

5. Creating the Migration

Once the model and DbContext are set up, the next step is to create a migration to generate the database schema.

Run the following command to create the migration:

dotnet ef migrations add InitialCreate

After the migration is created, apply it to the database:

dotnet ef database update

This will create the Products table in the database, using the properties defined in the Product model.

6. Creating the CRUD Operations in the Controller

Now, let’s create the ProductsController in the Controllers folder to handle CRUD operations for the Product model. This controller will contain actions for creating, reading, updating, and deleting products.

Create Product (POST)

[HttpPost]
public IActionResult Create([FromBody] Product product)
{
    if (product == null)
    {
        return BadRequest();
    }

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

Get All Products (GET)

[HttpGet]
public IActionResult GetAll()
{
    var products = _context.Products.ToList();
    return Ok(products);
}

Get Product by ID (GET)

[HttpGet("{id}")]
public IActionResult GetById(int id)
{
    var product = _context.Products.FirstOrDefault(p => p.Id == id);

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

    return Ok(product);
}

Update Product (PUT)

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

    var existingProduct = _context.Products.FirstOrDefault(p => p.Id == id);
    if (existingProduct == null)
    {
        return NotFound();
    }

    existingProduct.Name = product.Name;
    existingProduct.Price = product.Price;
    
    _context.SaveChanges();
    return NoContent();
}

Delete Product (DELETE)

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

    _context.Products.Remove(product);
    _context.SaveChanges();
    return NoContent();
}

7. Testing the API

Now that we have completed the controller, you can test the API using Postman or cURL to ensure the CRUD operations are working correctly.

  • POST a new product to /api/products.
  • GET all products from /api/products.
  • GET a single product by ID from /api/products/{id}.
  • PUT an existing product by ID to /api/products/{id}.
  • DELETE a product by ID from /api/products/{id}.

8. Conclusion

In this tutorial, we walked through the process of building a simple CRUD Web API with .NET Core and EF Core. We:

  • Created a basic Product model.
  • Set up the DbContext and database connection.
  • Implemented the CRUD operations (Create, Read, Update, and Delete) in the ProductsController.

By building this application, you’ve gained hands-on experience with Entity Framework Core, ASP.NET Core Web API, and SQL Server. This is just the beginning of what you can build with .NET Core and EF Core, and there are many more advanced features and tools to explore as you continue your journey.

Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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