Getting Started with Entity Framework

Entity Framework (EF) is a popular Object-Relational Mapper (ORM) for .NET that enables developers to work with relational data using domain-specific objects. It abstracts away much of the boilerplate data access code, allowing you to focus on your application's business logic.

What is Entity Framework?

Entity Framework allows you to query raw SQL and commands and then translates them into your chosen programming language. It allows you to define your data model using classes and properties and then interact with the database through these objects. This approach is often referred to as the "Code-First" or "Model-First" approach, depending on how you start.

Key Concepts

Installation

You can install Entity Framework via NuGet Package Manager. Open the Package Manager Console and run:

Install-Package EntityFramework
Tip: For newer projects, consider using Entity Framework Core, the latest generation of Entity Framework, which is a cross-platform, high-performance, extensible, and open-source version.

Creating Your First Entity Model (Code-First)

Let's create a simple model for a blog application.

  1. Define Your Entities: Create C# classes to represent your database tables.
    
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime PublishDate { get; set; }
    }
    
    public class Comment
    {
        public int Id { get; set; }
        public string Author { get; set; }
        public string Text { get; set; }
        public DateTime CommentDate { get; set; }
    
        public int PostId { get; set; }
        public Post Post { get; set; }
    }
                    
  2. Create Your DbContext: Inherit from DbContext and add DbSet<TEntity> properties for each entity.
    
    using System.Data.Entity;
    
    public class BlogContext : DbContext
    {
        public BlogContext() : base("name=BlogConnectionString")
        {
        }
    
        public DbSet<Post> Posts { get; set; }
        public DbSet<Comment> Comments { get; set; }
    }
                    
    Make sure to configure your connection string in your application's configuration file (e.g., App.config or Web.config).
  3. Enable Migrations: In the Package Manager Console, run:
    Enable-Migrations
    This command creates an initial migration file and a Migrations folder.
  4. Add an Initial Migration: Create the initial database schema based on your entities:
    Add-Migration InitialCreate
  5. Update the Database: Apply the migration to create the database:
    Update-Database

Querying Data

You can query your data using LINQ:


using (var context = new BlogContext())
{
    var posts = context.Posts.Where(p => p.PublishDate.Year == 2023).ToList();
    foreach (var post in posts)
    {
        Console.WriteLine($"Title: {post.Title}");
    }
}
        

Saving Data

Adding, updating, and deleting entities is straightforward:


using (var context = new BlogContext())
{
    // Add a new post
    var newPost = new Post
    {
        Title = "My First EF Post",
        Content = "This is the content of my first post.",
        PublishDate = DateTime.Now
    };
    context.Posts.Add(newPost);
    context.SaveChanges(); // Save changes to the database

    // Update a post
    var postToUpdate = context.Posts.Find(1); // Assuming a post with ID 1 exists
    if (postToUpdate != null)
    {
        postToUpdate.Title = "Updated Title";
        context.SaveChanges();
    }

    // Delete a post
    var postToDelete = context.Posts.Find(2); // Assuming a post with ID 2 exists
    if (postToDelete != null)
    {
        context.Posts.Remove(postToDelete);
        context.SaveChanges();
    }
}
        
Note: SaveChanges() persists all pending changes to the database.

Further Reading