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:
- Installing EF Core (NuGet packages)
- Setting up the DbContext
- Creating the first migration and database
- 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:
- From the File menu, select New > Project.
- Select Console App (.NET Core).
- Name the project something like "ProductApp".
- Click Create.
2. Add Layers (Projects)
- We’ll add two additional projects: one for the Domain Layer and another for the Data Layer.
- Right-click on the solution in Solution Explorer and select Add > New Project.
- Select Class Library and name the first project ProductDomain.
- 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.
- Right-click on ProductData and select Manage NuGet Packages.
- 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");
}
}
}
- 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; }
}
}
Category.cs:
namespace ProductDomain
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
}
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; }
}
}
6. Creating the First Migration and Database
- Open the Package Manager Console from Tools > NuGet Package Manager > Package Manager Console.
- Set the Default Project to ProductData.
- Run the following commands to create the migration and database:
Add-Migration InitialCreate
Update-Database
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();
}
}
}
}
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);
}
}
}
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)