MSDN .NET Documentation

.NET Concepts | Data Access | ADO.NET

Object-Relational Mapping (ORM) with Entity Framework

Entity Framework (EF) is a powerful Object-Relational Mapper (ORM) developed by Microsoft. It allows developers to work with relational data in a more object-oriented way, abstracting away much of the low-level database interaction code.

What is Object-Relational Mapping?

Object-Relational Mapping is a programming technique for converting data between incompatible type systems within object-oriented programming languages. In simpler terms, it bridges the gap between the object-oriented world of your application code and the relational world of your database.

Most modern applications use object-oriented languages (like C# or VB.NET), while databases typically store data in tables with rows and columns. These two paradigms are fundamentally different:

  • Object-Oriented: Deals with classes, objects, inheritance, and complex relationships.
  • Relational: Deals with tables, rows, columns, primary keys, and foreign keys.

An ORM like Entity Framework automates the translation between these two models, saving developers from writing repetitive SQL queries and mapping code.

Key Concepts in Entity Framework ORM

1. DbContext

The DbContext is the primary class for interacting with the database in Entity Framework. It represents a session with the database and allows you to query data, track changes, and save those changes back to the database.

Key responsibilities of DbContext:

  • Connection Management: Manages the connection to the database.
  • Change Tracking: Keeps track of all entities that have been loaded or added.
  • Querying: Provides methods to query entities from the database (e.g., using LINQ).
  • Saving Changes: Commits changes made to entities back to the database.

Example:


using (var context = new MyDbContext())
{
    // Querying data
    var products = context.Products.Where(p => p.Category == "Electronics").ToList();

    // Adding a new entity
    var newProduct = new Product { Name = "Widget", Price = 19.99m };
    context.Products.Add(newProduct);

    // Saving changes
    context.SaveChanges();
}
                

2. Entity

An entity in Entity Framework is a .NET class that maps to a table in your database. Instances of these classes represent individual rows in that table.

Example Entity Class:


public class Product
{
    public int ProductId { get; set; } // Primary Key
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }

    // Navigation property to represent a one-to-many relationship
    public virtual ICollection OrderLines { get; set; }
}
                

3. DbSet

A DbSet<TEntity> property on your DbContext represents a collection of all entities in the store for a given entity type. It's essentially a gateway to query and manipulate a specific table (entity set).

Example in DbContext:


public class MyDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderLine> OrderLines { get; set; }

    // Constructor and OnConfiguring methods would be here
}
                

4. LINQ to Entities

Language Integrated Query (LINQ) is a powerful feature in .NET that allows you to write queries against data sources using familiar C# or VB.NET syntax. Entity Framework leverages LINQ to translate your object-oriented queries into SQL queries that are executed against the database.

This abstraction allows you to write queries without knowing the underlying SQL syntax, making your code more readable and maintainable.

5. Entity States

Entity Framework tracks the state of each entity within the DbContext. This state determines how the entity will be handled when SaveChanges() is called.

Common Entity States:

  • Unchanged: The entity has not been modified since it was queried.
  • Added: The entity is new and will be inserted into the database.
  • Modified: The entity's properties have been changed and will be updated in the database.
  • Deleted: The entity will be removed from the database.
  • Detached: The entity is not being tracked by the DbContext.
Tip: Understanding entity states is crucial for efficient data manipulation and troubleshooting when saving changes.

Benefits of Using Entity Framework as an ORM

  • Increased Productivity: Reduces the amount of boilerplate data access code you need to write.
  • Improved Readability: LINQ queries are more expressive than raw SQL.
  • Abstraction: Decouples your application logic from the specific database schema.
  • Maintainability: Easier to refactor and maintain your data access layer.
  • Cross-Database Support: EF can work with various database providers (SQL Server, PostgreSQL, MySQL, SQLite, etc.) with minimal code changes.

When to Use Entity Framework

Entity Framework is suitable for a wide range of .NET applications, from small utilities to large enterprise systems. It's particularly beneficial when:

  • You need to interact with a relational database.
  • You prefer to work with objects rather than raw SQL.
  • You want to speed up development time for data access.
  • Your application has complex domain models.