Entity Framework (EF) is an open-source object-relational mapper (ORM) for .NET applications. It enables developers to work with a database using .NET objects, eliminating the need for most of the data-access code that developers usually need to write. In this module, we will cover the basics of Entity Framework, how to set it up, and how to perform CRUD (Create, Read, Update, Delete) operations.

Table of Contents

Introduction to Entity Framework

Entity Framework simplifies data access by allowing developers to interact with a database using .NET objects. It supports:

  • Code First: Define the model using C# classes, and EF will create the database schema.
  • Database First: Generate the model from an existing database.
  • Model First: Define the model using a visual designer, and EF will generate the database schema.

Setting Up Entity Framework

Step 1: Install Entity Framework

To use Entity Framework in your project, you need to install the EF package via NuGet. Open the Package Manager Console and run the following command:

Install-Package EntityFramework

Step 2: Configure the Connection String

Add a connection string to your App.config or Web.config file to specify the database connection details.

<configuration>
  <connectionStrings>
    <add name="MyDbContext"
         connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyDatabase;Integrated Security=True"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Creating a Data Model

Step 1: Define the Entity Classes

Create C# classes that represent the tables in your database.

public class Student
{
    public int StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime EnrollmentDate { get; set; }
}

Step 2: Create the DbContext

Create a class that inherits from DbContext to manage the entity objects during runtime.

public class SchoolContext : DbContext
{
    public DbSet<Student> Students { get; set; }

    public SchoolContext() : base("name=MyDbContext")
    {
    }
}

CRUD Operations

Create

Add a new student to the database.

using (var context = new SchoolContext())
{
    var student = new Student
    {
        FirstName = "John",
        LastName = "Doe",
        EnrollmentDate = DateTime.Now
    };
    context.Students.Add(student);
    context.SaveChanges();
}

Read

Retrieve students from the database.

using (var context = new SchoolContext())
{
    var students = context.Students.ToList();
    foreach (var student in students)
    {
        Console.WriteLine($"{student.FirstName} {student.LastName}");
    }
}

Update

Update an existing student's details.

using (var context = new SchoolContext())
{
    var student = context.Students.FirstOrDefault(s => s.StudentId == 1);
    if (student != null)
    {
        student.LastName = "Smith";
        context.SaveChanges();
    }
}

Delete

Remove a student from the database.

using (var context = new SchoolContext())
{
    var student = context.Students.FirstOrDefault(s => s.StudentId == 1);
    if (student != null)
    {
        context.Students.Remove(student);
        context.SaveChanges();
    }
}

Querying Data

Entity Framework provides a powerful querying capability using LINQ (Language Integrated Query).

Example: Retrieve Students Enrolled After a Certain Date

using (var context = new SchoolContext())
{
    var students = context.Students
                          .Where(s => s.EnrollmentDate > new DateTime(2020, 1, 1))
                          .ToList();
    foreach (var student in students)
    {
        Console.WriteLine($"{student.FirstName} {student.LastName}");
    }
}

Advanced Features

Lazy Loading

Entity Framework supports lazy loading, which means related data is automatically loaded from the database when accessed.

Eager Loading

Eager loading is the process of loading related data as part of the initial query.

using (var context = new SchoolContext())
{
    var students = context.Students.Include(s => s.Enrollments).ToList();
}

Code First Migrations

Code First Migrations allow you to evolve your database schema over time.

Enable-Migrations
Add-Migration InitialCreate
Update-Database

Practical Exercises

Exercise 1: Create a New Entity

  1. Define a new entity class Course with properties CourseId, Title, and Credits.
  2. Add a DbSet<Course> property to your SchoolContext.
  3. Create a new course and save it to the database.

Solution

public class Course
{
    public int CourseId { get; set; }
    public string Title { get; set; }
    public int Credits { get; set; }
}

public class SchoolContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    public SchoolContext() : base("name=MyDbContext")
    {
    }
}

// Adding a new course
using (var context = new SchoolContext())
{
    var course = new Course
    {
        Title = "Introduction to C#",
        Credits = 3
    };
    context.Courses.Add(course);
    context.SaveChanges();
}

Summary

In this module, we covered the basics of Entity Framework, including setting it up, creating a data model, and performing CRUD operations. We also explored querying data and some advanced features like lazy loading and migrations. By completing the practical exercises, you should now have a solid understanding of how to use Entity Framework in your C# applications.

© Copyright 2024. All rights reserved