How to use Entity Framework with concrete C# Examples

awjanthiel
•

How To Use Entity Framework With Concrete C# Examples. A Hands-On Guide.

Entity Framework (EF) is a powerful Object-Relational Mapper for .NET developers that simplifies data access by allowing you to work with databases using C# objects instead of raw SQL queries. This article offers a practical introduction to using Entity Framework with concrete C# examples to get you started quickly and effectively.

Getting Started With Entity Framework Core

Before diving into code, you need to install the Entity Framework Core package in your project. You can do this using the NuGet Package Manager Console:

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer

These commands install the core EF libraries along with SQL Server provider. For other databases, there are different providers available.

Defining Your Data Model

Start by creating your entity classes. These classes represent tables in your database. For example, a simple Product entity might look like this:

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

This class will correspond to a Products table in your database with columns ProductId, Name, and Price.

Creating The DbContext

The DbContext manages your entity objects during runtime, including querying and saving data. Define a ProductContext for your Product entity:

using Microsoft.EntityFrameworkCore;

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("YourConnectionStringHere");
    }
}

Replace YourConnectionStringHere with your actual database connection string.

Code-First Migration and Database Creation

EF Core supports a code-first approach where the database schema can be created from your code. Initialize migrations from the Package Manager Console:

Add-Migration InitialCreate
Update-Database

These commands generate SQL to create tables based on your entities and apply it to your database.

Adding Data To The Database

Let’s insert a new product using EF Core:

using (var context = new ProductContext())
{
    var product = new Product { Name = "Laptop", Price = 999.99M };
    context.Products.Add(product);
    context.SaveChanges();
}

This code creates a new product entity, adds it to the Products set, and saves changes to the database.

Querying Data From The Database

Querying is just as simple. Here’s how to fetch all products:

using (var context = new ProductContext())
{
    var products = context.Products.ToList();
    foreach (var p in products)
    {
        Console.WriteLine($"Product: {p.Name}, Price: {p.Price}");
    }
}

You can also filter results using LINQ expressions:

var expensiveProducts = context.Products
    .Where(p => p.Price > 500)
    .ToList();

Updating An Existing Entity

To update a product’s price, first retrieve it, modify the property, then save changes:

using (var context = new ProductContext())
{
    var product = context.Products.First(p => p.Name == "Laptop");
    product.Price = 899.99M;
    context.SaveChanges();
}

Deleting An Entity

To remove a product:

using (var context = new ProductContext())
{
    var product = context.Products.Find(1);
    if (product != null)
    {
        context.Products.Remove(product);
        context.SaveChanges();
    }
}

Summary

Entity Framework Core abstracts database operations into simple C# code, making data access intuitive and less error-prone. By defining your models, configuring DbContext, running migrations, and using standard C# interactions, you can build robust data-driven applications quickly.

This article showed you the core steps and concrete examples to get started. As you grow more comfortable, explore EF Core’s advanced features like relationship mappings, asynchronous operations, and change tracking.