Entity Framework Core (EF Core) is a modern, cross-platform, open-source version of the popular Entity Framework data access technology. It provides a familiar abstraction layer over your database, allowing you to work with data using .NET objects.
EF Core enables you to:
Before you begin, ensure you have the following installed:
You can install EF Core using the .NET CLI. For example, to add the SQL Server provider to your project:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
You'll also typically need the design-time tools for migrations:
dotnet add package Microsoft.EntityFrameworkCore.Design
Create Plain Old CLR Objects (POCOs) that represent your database tables.
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public string Title { get; set; }
public virtual List<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 Blog Blog { get; set; }
}
The DbContext
class is the main entry point for interacting with your database.
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Replace with your actual connection string
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;");
}
}
DbContext
using dependency injection in ASP.NET Core applications rather than overriding OnConfiguring
.
EF Core Migrations allow you to incrementally update your database schema as your model changes.
First, create an initial migration:
dotnet ef migrations add InitialCreate
Then, apply the migration to create the database:
dotnet ef database update
Microsoft.EntityFrameworkCore.Design
package installed and the EF Core tools are available in your PATH.
Now you can use your DbContext
to interact with the database.
using (var context = new BloggingContext())
{
// Add a new blog
var blog = new Blog { Url = "http://example.com", Title = "My First Blog" };
context.Blogs.Add(blog);
context.SaveChanges();
// Query blogs
var query = from b in context.Blogs
orderby b.Url
select b;
foreach (var item in query)
{
Console.WriteLine($"Blog: {item.Title} ({item.Url})");
}
// Add a post to an existing blog
blog.Posts.Add(new Post { Title = "Hello World", Content = "This is my first post!" });
context.SaveChanges();
}
DbContext
: Represents a session with the database and allows you to query and save data.DbSet<TEntity>
: Represents a collection of entities in the context, which can be used for read, add, delete, and update operations.Explore these advanced topics: