.NET Documentation

Entity Framework Overview

Entity Framework (EF) is a set of data access technologies developed by Microsoft that enables .NET developers to interact with relational databases using domain-specific objects. It is an Object-Relational Mapper (ORM) that eliminates the need for most of the data-access coding that developers traditionally need to write.

What is Entity Framework?

Entity Framework allows you to query, insert, update, and delete data using a model that is specific to your application's domain, rather than interacting directly with database tables and columns. This abstraction simplifies data access and improves developer productivity.

Key Concepts

Core Features and Benefits

Object-Relational Mapping (ORM)

Translate database tables and columns into C# objects and properties. Work with data as if it were just .NET objects.

LINQ to Entities

Use Language Integrated Query (LINQ) to write queries against your entities directly in C# or Visual Basic. EF translates these queries into efficient SQL.

Database First, Model First, Code First

Choose your development approach: generate a model from an existing database (Database First), design your model visually and generate the database (Model First), or define your model using C# classes and let EF create the database (Code First).

Change Tracking

EF automatically tracks changes made to entities, so when you call SaveChanges(), it generates the necessary SQL INSERT, UPDATE, or DELETE statements.

Migrations

Manage schema changes over time. EF Migrations can automatically update your database schema as your entity models evolve.

Performance Optimization

EF provides features like query caching, eager loading, and lazy loading to help optimize data retrieval performance.

Getting Started

The easiest way to get started with Entity Framework is by using the Code First approach.

  1. Install the Microsoft.EntityFrameworkCore NuGet package.
  2. Define your entity classes (POCOs).
  3. Define your DbContext class, inheriting from DbContext and including DbSet<TEntity> properties for your entities.
  4. Configure your database connection.

Example: Code First Setup

// Define an entity
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Define the DbContext
public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Replace with your actual connection string
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }
}

Further Reading