(Notes from Pluralsight/ASP.NET Core 6 Fundamentals)
overview
Prior to Entity Framework Core, the approach to bring data into a web app was ADO.NET. This was low-level and required developers to know a lot of SQL. EF Core makes this easier.
EF Core looks for a property named Id
or ClassNameId
and makes that the Primary Key in the database.
ef core change tracking
The EF Core Data context keeps tracks of changes in data objects and updates them in the database.
adding ef core to an app
- Add packages
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
for various commands and support for migrations
- Create domain classes
- Table names are created on the plural of the model class
- Columns are created based on the properties of the model class
- EF Core will create a Foreign Key for any other type used in this model class
- Create a Database Context
DbContext
is the bridge between the app’s code and the database- It manages entity objects during application runtime
- It persists data back to the database
public class BethanysPieShopDbContext : DbContext { public BethanysPieShopDbContext(DbContextOptions<BethanysPieShopDbContext> options) { // a DbSet signals to EF Core that there will be a table (Pie) in the database. // This property allows us to access records in that table. public DbSet<Pie> Pies { get; set; } } }
- Add a connection string
The connection string tells the code how to connect to the database.
It is placed in
appsettings.json:
{ "ConnectionStrings": { "Server=(localdb)\mssqllocaldb; Database=BethanysPieShop; Trust_Connection=True; MultipleActiveResultsSets=true" } }
- Wire up the database in
Program.cs
builder.Services.AddDbContext<BethanysPieShopDbContext>( options => { options.UseSqlServer( builder.Configuration["ConnectionStrings:BethanysPieShopDbContextConnection"]); })
querying for data using linq
_bethanysPieShopDbContext.Pies // return Pies
.Include(c => c.Category) // including the Category to which they belong (a different table)
.Where(p => p.IsPieOfTheWeek); // but only the pies that are PieOfTheWeek