Entity Framework Core: Getting Started
Welcome to the getting started guide for Entity Framework Core (EF Core), Microsoft's modern, cross-platform Object-Relational Mapper (ORM) for .NET. EF Core makes it easier for developers to work with databases by enabling them to use .NET objects instead of database tables. This guide will walk you through the essential steps to get up and running with EF Core.
1. Installation
First, you need to install the necessary NuGet packages. You can do this using the .NET CLI or the NuGet Package Manager in Visual Studio.
Using the .NET CLI:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer # Or your chosen database provider
For example, to use SQL Server, you would install the Microsoft.EntityFrameworkCore.SqlServer
package. Other popular providers include SQLite, PostgreSQL, MySQL, and more.
2. Define Your Model
EF Core uses Plain Old CLR Objects (POCOs) to represent your database tables. Define C# classes that correspond to the entities you want to store in your database.
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public ICollection 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; }
}
3. Create Your DbContext
The DbContext
is your primary interface with the database. It represents a session with the database and allows you to query and save data. It's also where you configure your entities.
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
public DbSet Blogs { get; set; }
public DbSet Posts { get; set; }
public BloggingContext(DbContextOptions<BloggingContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Optional: Configure relationships or constraints here
modelBuilder.Entity<Blog>().Property(b => b.Url).IsRequired();
}
}
4. Configure the Connection and DbContext
You need to tell EF Core how to connect to your database. This is typically done in your application's startup configuration.
Example using Dependency Injection in ASP.NET Core (Program.cs
or Startup.cs
):
var connectionString = "Server=(localdb)\\mssqllocaldb;Database=BloggingDB;Trusted_Connection=True;";
builder.Services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(connectionString));
5. Create the Database
With EF Core, you can leverage Migrations to create and update your database schema based on your model changes. To create the initial database:
First, enable Migrations:
dotnet ef migrations add InitialCreate
Then, apply the migration to create the database:
dotnet ef database update
6. Querying and Saving Data
Now you can start interacting with your database using your DbContext
.
using var context = new BloggingContext(options); // Or inject DbContext
// Add a new blog
context.Blogs.Add(new Blog { Url = "http://sample.com" });
context.SaveChanges();
// Query blogs
var blogs = context.Blogs.ToList();
// Find a specific blog and add a post
var firstBlog = context.Blogs.FirstOrDefault();
if (firstBlog != null)
{
firstBlog.Posts.Add(new Post { Title = "Hello EF Core", Content = "This is my first post." });
context.SaveChanges();
}