Entity Framework Basics
Entity Framework (EF) is an object-relational mapper (ORM) that enables developers to work with relational data using domain-specific objects that are conceptually clean (models) instead of the underlying data store it often transparently maps. EF Core is the cross-platform, open-source, and extensible version of the data access technology for .NET.
What is Entity Framework?
Entity Framework allows you to:
- Query data from your database using LINQ (Language Integrated Query).
- Persist changes made to your objects back to the database.
- Define your database schema based on your object models (Code-First approach) or generate models from an existing database (Database-First approach).
- Manage database migrations to evolve your schema over time.
Core Concepts
Understanding these core concepts is crucial:
- DbContext: The primary class that represents a session with the database and allows you to query and save data.
-
DbSet<TEntity>: Represents a collection of all entities in the context, or that can be queried from the database, of a given type. In essence, a
DbSet<TEntity>
corresponds to a table in the database. - Entities: Plain Old CLR Objects (POCOs) that represent tables or views in your database.
- Migrations: A feature that allows you to manage incremental changes to your database schema as your application evolves.
Getting Started with Code-First
The Code-First approach allows you to define your domain models first, and then have EF Core create the database for you. Here's a simplified example:
1. Define Your Models
Create classes to represent your entities:
// Models/Blog.cs
public class Blog
{
public int BlogId { get; set; } // Primary Key
public string Url { get; set; }
public virtual ICollection<Post> Posts { get; set; } // Navigation Property
}
// Models/Post.cs
public class Post
{
public int PostId { get; set; } // Primary Key
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; } // Foreign Key
public virtual Blog Blog { get; set; } // Navigation Property
}
2. Define Your DbContext
Create a class that inherits from DbContext
:
// Data/BlogContext.cs
using Microsoft.EntityFrameworkCore;
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Specify the connection string for your database
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=EFBasicsDb;Trusted_Connection=True;");
}
// Optional: Configure relationships using Fluent API if needed
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Example: Define a one-to-many relationship between Blog and Post
modelBuilder.Entity<Blog>()
.HasMany<Post>(b => b.Posts)
.WithOne(p => p.Blog)
.HasForeignKey(p => p.BlogId);
}
}
3. Enable Migrations
You'll need the EF Core tools installed. Typically, you'll use the NuGet Package Manager Console or the .NET CLI.
Using .NET CLI:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet ef migrations add InitialCreate
dotnet ef database update
Querying Data
Once your database is set up, you can query data using LINQ:
using (var context = new BlogContext())
{
// Get all blogs
var blogs = context.Blogs.ToList();
// Get blogs with posts
var blogsWithPosts = context.Blogs.Include(b => b.Posts).ToList();
// Find a specific blog by URL
var specificBlog = context.Blogs.FirstOrDefault(b => b.Url.Contains("example.com"));
// Find posts with a specific title
var matchingPosts = context.Posts.Where(p => p.Title.Contains("Introduction")).ToList();
}
Saving Data
Adding, updating, and deleting entities is straightforward:
using (var context = new BlogContext())
{
// Add a new blog
var newBlog = new Blog { Url = "https://newblog.com" };
context.Blogs.Add(newBlog);
context.SaveChanges(); // Persist changes to the database
// Add a new post to an existing blog
var existingBlog = context.Blogs.Find(1); // Assuming blog with ID 1 exists
if (existingBlog != null)
{
var newPost = new Post { Title = "My First Post", Content = "This is the content.", Blog = existingBlog };
context.Posts.Add(newPost);
context.SaveChanges();
}
// Update an entity
var blogToUpdate = context.Blogs.Find(1);
if (blogToUpdate != null)
{
blogToUpdate.Url = "https://updatedblog.com";
context.SaveChanges();
}
// Delete an entity
var blogToDelete = context.Blogs.Find(2); // Assuming blog with ID 2 exists
if (blogToDelete != null)
{
context.Blogs.Remove(blogToDelete);
context.SaveChanges();
}
}
Note: Always ensure you call SaveChanges()
to persist your changes to the database.
Further Reading
For more advanced topics like relationships, performance tuning, and advanced querying, please refer to the official Microsoft documentation.