Working with Real Data
Using Entity Framework Core
Gill Cleeren
CTO XPIRIT BELGIUM
@gillcleeren www.snowball.be
Overview Hello EF Core
Adding EF Core to the application
Initializing the database
Modifying the model
Hello EF Core
Entity Framework Core (EF Core)
Lightweight &
ORM LINQ support
Cross-platform
SQL Server and
Open-source other, non-relational Code-first
DB support
EF Core
Entity Framework
Code Database
What EF Core Does for You
Class Table
public class Pie
{ PieId Int (PK)
public int PieId { get; set; } Name String
public string Name { get; set; }
public string Description { get; set; } Description string
}
Adding EF Core to the Application
Adding EF Core to the Application
Domain classes Database context
Application configuration Packages (.NET Core 3)
The Database Context
public class AppDbContext : DbContext
{
public AppDbContext
(DbContextOptions<AppDbContext> options): base(options)
{
}
public DbSet<Pie> Pies { get; set; }
}
Adding EF Core to the Application
Domain classes Database context
Application configuration Packages (.NET Core 3)
Connection String in AppSettings.json
{
"ConnectionStrings": {
"DefaultConnection":
"Server=(localdb)\\mssqllocaldb;
Database=BethanysPieShop;
Trusted_Connection=True;
MultipleActiveResultSets=true“
}
}
Startup Changes
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString
("DefaultConnection")));
}
Adding EF Core to the Application
Domain classes Database context
Application configuration Packages (.NET Core 3/5)
Demo
Adding the required packages
Creating the DbContext
Changing the application configuration
_appDbContext.Pies.
Include(c => c.Category).Where(p => p.IsPieOfTheWeek);
Querying for Data
Modifying Data
foreach (var shoppingCartItem in shoppingCartItems)
{
var orderDetail = new OrderDetail
{
Amount = shoppingCartItem.Amount,
PieId = shoppingCartItem.Pie.PieId,
Price = shoppingCartItem.Pie.Price
};
order.OrderDetails.Add(orderDetail);
}
_appDbContext.Orders.Add(order);
_appDbContext.SaveChanges();
Demo
Creating the real repository
Creating and Initializing the Database
Creating the Database
Create database
Database migration
Database
Package Manager Console
Commands
>add-migration <MigrationName>
>update-database
Initializing the Database
Initial data
HasData() on the Database
DbContext (migration)
Demo
Creating the database
Initializing the database
Modifying the Model
Modifying the Model
Update database
Model change Database
Database migration
Commands
>add-migration <MigrationName>
>update-database
Demo
Modifying the model
Updating the database
Summary EF Core is the ORM for ASP.NET Core
MVC applications
Code-first
Migrations are used to create and modify
the database
Up next:
Adding navigation to the site