What is Entity Framework Core and why is it needed
Entity Framework Core (EF Core) is a modern object-relational mapper (ORM) for the .NET platform, developed by Microsoft. It allows developers to work with databases using .NET objects and eliminates the need to write most of the data access code.
EF Core is a lightweight, extensible, and cross-platform version of Entity Framework. It supports many DBMS, including SQL Server, SQLite, PostgreSQL, MySQL, Oracle, and others.
Key features of EF Core:
- Automatic creation and updating of the database schema based on the model (Code First)
- Querying the database using LINQ (Language Integrated Query)
- Automatic change tracking of objects and generation of SQL commands for data updates
- Support for migrations to manage database schema changes
- Support for relationships between entities (one-to-one, one-to-many, many-to-many)
- Lazy, eager, and explicit loading of related data
Installing Entity Framework Core
Installing EF Core is done via NuGet Package Manager. Unlike Python, here you use dotnet add package or the Visual Studio package manager.
Installation via .NET CLI:
dotnet add package Microsoft.EntityFrameworkCoredotnet add package Microsoft.EntityFrameworkCore.SqlServerdotnet add package Microsoft.EntityFrameworkCore.ToolsInstallation for PostgreSQL (Npgsql):
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQLInstallation for SQLite:
dotnet add package Microsoft.EntityFrameworkCore.SqliteInstallation for MySQL:
dotnet add package Pomelo.EntityFrameworkCore.MySqlQuick start with a code example
Let's create a simple console application for working with a book database.
1. Create the data model:
public class Book{ public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } public int Year { get; set; } public decimal Price { get; set; }}
public class Author{ public int Id { get; set; } public string Name { get; set; } public List<Book> Books { get; set; } = new();}2. Create the database context:
public class LibraryContext : DbContext{ public DbSet<Book> Books { get; set; } public DbSet<Author> Authors { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=library.db"); }}3. Use EF Core to work with data:
using var context = new LibraryContext();context.Database.EnsureCreated(); // Create the database if it doesn't exist
// Adding datavar author = new Author { Name = "Leo Tolstoy" };author.Books.Add(new Book { Title = "War and Peace", Year = 1869, Price = 1500m });author.Books.Add(new Book { Title = "Anna Karenina", Year = 1877, Price = 1200m });
context.Authors.Add(author);context.SaveChanges();
// Reading datavar books = context.Books .Where(b => b.Year > 1850) .OrderBy(b => b.Year) .ToList();
foreach (var book in books){ Console.WriteLine($"{book.Title} ({book.Year})");}Main methods and functions of Entity Framework Core
1. Add
Description: Adds a new entity to the context in the Added state. When SaveChanges() is called, an INSERT command will be executed.
Parameters:
object entity
Also in library
Event Bus and Observer Pattern in Kotlin: A Guide with Examples
Working with S3 and Cloud Storage in TypeScript: Libraries and Examples
Working with Dates in Swift: Foundation, SwiftDate, DateTools (iOS/macOS)
Swift CLI with ArgumentParser: Creating Powerful Console Tools
C# (.NET) Application Configuration: Microsoft.Extensions.Configuration