Sub topic 1
What EF Core Is and Why Use an ORM
What an ORM does
A database stores data in tables made of rows and columns. A C# program works with objects instead. An ORM (object-relational mapper) is a library that translates between the two. You work with C# objects, and the ORM writes the SQL for you.
Entity Framework Core (EF Core) is Microsoft's ORM for .NET. It saves you from writing repetitive SQL by hand. Your code also stays mostly the same if you later switch databases.
Setting up the project
A provider is a package that teaches EF Core to talk to one kind of database. This tutorial uses SQLite, a small database that lives in a single file. Run these commands:
dotnet new console -o EfCoreDemo
cd EfCoreDemo
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install --global dotnet-efThe Design package and the dotnet-ef tool are needed later for migrations.
Entity classes, DbContext, and DbSet
An entity is a plain C# class that maps to a table. EF Core follows conventions, which are default rules. One rule says a property named Id or BlogId becomes the primary key. Another says Post.BlogId becomes a foreign key that points to a blog.
A DbContext is the class that represents your connection to the database. Each DbSet<T> property on it stands for one table.
Add a file named Model.cs:
using Microsoft.EntityFrameworkCore;
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
public List<Post> Posts { get; } = new();
}
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; } = null!;
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs => Set<Blog>();
public DbSet<Post> Posts => Set<Post>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=blogging.db");
}Provider and connection string
UseSqlite selects the provider. The text "Data Source=blogging.db" is the connection string, which tells the provider where the database is. To use SQL Server instead, you would install its provider and call UseSqlServer with a different connection string.
Exercise
In the model above, which property is the primary key of Post, and which property links each post to its blog?
Show answer
PostId is the primary key, because it follows the "ClassName + Id" convention. BlogId is the foreign key that links each post to its blog.