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
- DbContext: The primary class that represents a session with the database and allows you to query and save data.
- DbSet: Represents a collection of all entities in the context, or that can be queried from a given database.
- Entities: Plain Old CLR Objects (POCOs) that represent the tables in your database.
- Migrations: A feature that allows you to evolve your database schema over time as your model changes.
Installation
You can install Entity Framework via NuGet Package Manager. Open the Package Manager Console and run:
Install-Package EntityFramework
Creating Your First Entity Model (Code-First)
Let's create a simple model for a blog application.
-
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; } }
-
Create Your DbContext: Inherit from
DbContext
and addDbSet<TEntity>
properties for each entity.
Make sure to configure your connection string in your application's configuration file (e.g.,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; } }
App.config
orWeb.config
). -
Enable Migrations: In the Package Manager Console, run:
This command creates an initial migration file and aEnable-Migrations
Migrations
folder. -
Add an Initial Migration: Create the initial database schema based on your entities:
Add-Migration InitialCreate
-
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();
}
}
SaveChanges()
persists all pending changes to the database.