DEV Community

mohamed Tayel
mohamed Tayel

Posted on

EFCore Tutorial P1: Getting Started with EF Core

In this article, we’ll walk through setting up Entity Framework Core (EF Core) in a console application using a layered architecture. We’ll cover:

  1. Installing EF Core (NuGet packages)
  2. Setting up the DbContext
  3. Creating the first migration and database
  4. Basic CRUD operations (Create, Read, Update, Delete) using a ProductService

We will also ensure clean code by organizing logic into services, making the code easier to maintain and scale.

1. Create the Project

  • First, let's create a Console Application with a layered architecture. Open Visual Studio and follow these steps:
  1. From the File menu, select New > Project.
  2. Select Console App (.NET Core).
  3. Name the project something like "ProductApp".
  4. Click Create.

2. Add Layers (Projects)

  • We’ll add two additional projects: one for the Domain Layer and another for the Data Layer.
  1. Right-click on the solution in Solution Explorer and select Add > New Project.
  2. Select Class Library and name the first project ProductDomain.
  3. Add another Class Library project and name it ProductData.

Your solution should now have three projects:

  • ProductApp (Console Application)
  • ProductDomain (Domain Layer)
  • ProductData (Data Layer)

3. Install EF Core Packages

  • Now we need to install the necessary Entity Framework Core packages in the ProductData project.
  1. Right-click on ProductData and select Manage NuGet Packages.
  2. Search for and install the following packages:
    • Microsoft.EntityFrameworkCore
    • Microsoft.EntityFrameworkCore.SqlServer
    • Microsoft.EntityFrameworkCore.Tools

4. Setting Up the DbContext

In the ProductData project, create a new class called AppDbContext. This class will manage database access and link our application to the database.

using Microsoft.EntityFrameworkCore;
using ProductDomain;

namespace ProductData
{
    public class AppDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Inventory> Inventories { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Your_Connection_String_Here");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Replace "Your_Connection_String_Here" with your actual database connection string.

5. Creating the Domain Entities

In the ProductDomain project, add three classes for Product, Category, and Inventory. Here's an example:

Product.cs:

namespace ProductDomain
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

Category.cs:

namespace ProductDomain
{
    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<Product> Products { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

Inventory.cs:

namespace ProductDomain
{
    public class Inventory
    {
        public int Id { get; set; }
        public int ProductId { get; set; }
        public Product Product { get; set; }
        public int Quantity { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Creating the First Migration and Database

  1. Open the Package Manager Console from Tools > NuGet Package Manager > Package Manager Console.
  2. Set the Default Project to ProductData.
  3. Run the following commands to create the migration and database:
   Add-Migration InitialCreate
   Update-Database
Enter fullscreen mode Exit fullscreen mode

This will create the database with the Product, Category, and Inventory tables.

7. Creating the ProductService

Instead of placing all logic in the Main method, we’ll create a service to handle product-related operations. This will make the code cleaner and more scalable.

Create a new class ProductService.cs in the ProductData project:

using ProductDomain;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ProductData
{
    public class ProductService
    {
        private readonly AppDbContext _context;

        public ProductService(AppDbContext context)
        {
            _context = context;
        }

        public void CreateProduct(string productName, decimal price, string categoryName)
        {
            var category = new Category { Name = categoryName };
            var product = new Product { Name = productName, Price = price, Category = category };
            _context.Products.Add(product);
            _context.SaveChanges();
        }

        public List<Product> GetAllProducts()
        {
            return _context.Products.Include(p => p.Category).ToList();
        }

        public void UpdateProductPrice(int productId, decimal newPrice)
        {
            var product = _context.Products.FirstOrDefault(p => p.Id == productId);
            if (product != null)
            {
                product.Price = newPrice;
                _context.SaveChanges();
            }
        }

        public void DeleteProduct(int productId)
        {
            var product = _context.Products.FirstOrDefault(p => p.Id == productId);
            if (product != null)
            {
                _context.Products.Remove(product);
                _context.SaveChanges();
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

8. Update Program.cs to Use the Service

Now, instead of writing the CRUD logic in the Main method, we’ll delegate these operations to the ProductService.

In ProductApp (Console Application), update Program.cs as follows:

using ProductData;
using System;

class Program
{
    static void Main(string[] args)
    {
        using (var context = new AppDbContext())
        {
            var productService = new ProductService(context);

            // Create a product
            productService.CreateProduct("Laptop", 999.99M, "Electronics");

            // Read all products
            var products = productService.GetAllProducts();
            foreach (var product in products)
            {
                Console.WriteLine($"Product: {product.Name}, Category: {product.Category.Name}, Price: {product.Price}");
            }

            // Update product price
            var productIdToUpdate = products[0].Id;
            productService.UpdateProductPrice(productIdToUpdate, 899.99M);

            // Delete the product
            var productIdToDelete = products[0].Id;
            productService.DeleteProduct(productIdToDelete);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we created a simple EF Core setup with a console application, focusing on clean code through the use of services. We covered:

  • Installing EF Core
  • Setting up the DbContext
  • Creating the first migration and database
  • Performing basic CRUD operations

This structured approach ensures maintainability and prepares the project for future scalability. In the following articles, we’ll explore more advanced topics such as configuring relationships, handling migrations, and optimizing performance.
Source Code EFCoreDemo

Top comments (0)