Entity Framework Core Concepts
Entity Framework Core (EF Core) is a modern, cross-platform, open-source version of the popular Entity Framework data access technology. EF Core provides a lightweight, extensible data access platform for .NET developers.
What is Entity Framework Core?
EF Core allows developers to work with a DbContext
, which represents a session with the database and can be used to query and save data. EF Core maps your domain objects to the database schema, abstracting away much of the underlying data access complexity. It supports a wide range of relational databases, including SQL Server, PostgreSQL, MySQL, SQLite, Oracle, and more.
Key Concepts
1. DbContext
The DbContext
is the primary class used to interact with the database. It represents a session with the database and allows you to query and save data. You typically derive from DbContext
to create a custom context class.
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
}
}
2. DbSet<TEntity>
A DbSet<TEntity>
represents a collection of all entities in the store (e.g., all `Blog` objects in the database). It can be used to query the database. Instances of DbSet<TEntity>
are usually accessed from a DbContext
instance.
Example:
using (var context = new BloggingContext())
{
var blogs = context.Blogs.ToList(); // Query all blogs
}
3. Models and Entities
EF Core uses Plain Old CLR Objects (POCOs) as your domain models, often referred to as entities. These classes represent the data you store in your database. EF Core maps these entities to database tables.
Example Entities:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
4. Conventions
EF Core uses a set of default conventions to automatically configure the database schema based on your entity models. For example, it assumes that a property named `Id` or `ClassNameId` is the primary key. You can override these conventions using data annotations or the Fluent API.
5. Data Annotations
Attributes provided by .NET that you can apply to your entity classes and properties to configure the model. For example, [Key]
, [Required]
, [MaxLength]
.
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
public class Product
{
[Key]
public int ProductId { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
public decimal Price { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
6. Fluent API
The Fluent API provides a more programmatic way to configure your model, allowing for fine-grained control over mappings, relationships, and constraints. This is done within the OnModelCreating
method of your DbContext
.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired();
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts)
.HasForeignKey(p => p.BlogId);
}
7. Change Tracking
EF Core tracks changes made to entities fetched from the database. When you call SaveChanges()
, EF Core generates and executes the necessary SQL commands (INSERT, UPDATE, DELETE) to persist those changes.
8. Querying
EF Core provides LINQ (Language Integrated Query) support for querying your data. You can write queries using LINQ syntax that EF Core translates into SQL.
// Find a blog by URL
var blog = context.Blogs.FirstOrDefault(b => b.Url.Contains("example.com"));
// Get all posts for a specific blog
var posts = context.Posts.Where(p => p.BlogId == blog.BlogId).ToList();
9. Migrations
EF Core Migrations is a powerful feature that allows you to evolve your database schema over time as your application's models change. Migrations track changes to your EF Core model and can be used to create or update your database schema.
Conclusion
Understanding these core concepts is fundamental to effectively using Entity Framework Core. By leveraging DbContext
, DbSet
, entity modeling, and the powerful querying and migration features, developers can build robust and maintainable data-driven applications.