Chapter 10: Working with Data Using Entity Framework Core Flashcards
What are the most common places to store data?
Rational Database Management System (RDBMS) - SQL Server, PostgreSQL, MySQL, and SQLite
& NoSql - Azure
Cosmos DB, Redis, MongoDB, and Apache Cassandra
What are two approaches to working with EF Core
Database First
Code First
How to create SQLite database with cli?
sqlite3 Northwind.db -init Northwind4SQLite.sql
How to tell Visual Studio 2022 to copy the database file to the directory that it runs the code in so that it
can find the file, but only if the database file is newer or is missing?
<ItemGroup>
<None>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup
</ItemGroup>
Ef core sql server database provider
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SQLite
Microsoft.EntityFrameworkCore.InMemory
Microsoft.EntityFrameworkCore.Cosmos
Ef core Mysql database provider
MySQL.EntityFrameworkCore
Ef core Oracle DB 11.2 database provider
Oracle.EntityFrameworkCore
Ef core PostgreSQL database provider
Npgsql.EntityFrameworkCore.PostgreSQL
How to defining the Northwind database context class?
using Microsoft.EntityFrameworkCore;
public class Northwind : DbContext
{
protected override void OnConfiguring(
DbContextOptionsBuilder optionsBuilder)
{
string path = Path.Combine(Environment.CurrentDirectory, “Northwind.db”);
string connection = $”Filename={path}”;
optionsBuilder.UseSqlite(connection); } }
What is the EF Core conventions to define the model?
- The name of a table is assumed to match the name of a DbSet<T> property in the DbContext
class, for example, Products.</T> - The names of the columns are assumed to match the names of properties in the entity model
class, for example, ProductId. - The string .NET type is assumed to be a nvarchar type in the database.
- The int .NET type is assumed to be an int type in the database.
- The primary key is assumed to be a property that is named Id or ID, or when the entity model
class is named Product, then the property can be named ProductId or ProductID. If this
property is an integer type or the Guid type, then it is also assumed to be an IDENTITY column
(a column type that automatically assigns a value when inserting)
What is the EF Core annotation attributes to define the model?
[Required]
[StringLength(50)]
[RegularExpression(expression)]
[Column(TypeName = “money”, Name = “UnitPrice”)]
example:
[Required]
[StringLength(40)]
public string ProductName { get; set; }
How to using the EF Core Fluent API to define the model?
public class Northwind : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.Property(product => product.ProductName)
.IsRequired()
.HasMaxLength(40);</Product>
How to seeding data in EF Core with the Fluent API
modelBuilder.Entity<Product>()
.HasData(new Product
{
ProductId = 1,
ProductName = "Chai",
UnitPrice = 8.99M
});</Product>
What is the lazy loading feature
The two properties that relate the two entities, Category.Products and Product.Category, are both
marked as virtual
In Product Model
public virtual Category Category { get; set; } = null!;
in Category Model
public virtual ICollection<Product> Products { get; set; }</Product>
How to adding tables to the Northwind database context class?
public class Northwind : DbContext
{
// these properties map to tables in the database
public DbSet<Category>? Categories { get; set; }
public DbSet<Product>? Products { get; set; }</Product></Category>
What is the dotnet-ef tool?
The .NET CLI tool named dotnet can be extended with capabilities useful for working with EF Core
What is the meaning of scaffolding models using an existing database?
scaffolding create all the models & context from existing database
actually this is the reverse engineering templates tool
What is the scaffolding command for creating models from existing database?
dotnet ef dbcontext scaffold “Filename=Northwind.db” Microsoft.
EntityFrameworkCore.Sqlite –table Categories –table Products –outputdir AutoGenModels –namespace WorkingWithEFCore.AutoGen –dataannotations –context Northwind
How to query Categories table with ef core
IQueryable<Category>? categories;
categories = db.Categories?.Include(c => c.Products);
if ((categories is null) || (!categories.Any()))
{
Fail("No categories found.");
return;
}</Category>
foreach (Category c in categories)
{
WriteLine($”{c.CategoryName} has {c.Products.Count} products.”);
}
How to filtering included entities?
IQueryable<Category>? categories = db.Categories?
.Include(c => c.Products.Where(p => p.Stock >= stock));</Category>
How to sorting products
IQueryable<Product>? products = db.Products?
.Where(product => product.Cost > price)
.OrderByDescending(product => product.Cost);</Product>
How to getting the generated SQL
categories.ToQueryString()
How to logging EF Core
protected override void OnConfiguring(
DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.LogTo(WriteLine)
.EnableSensitiveDataLogging();
How to filtering logs by provider-specific values
optionsBuilder.LogTo(WriteLine, // Console
new[] { RelationalEventId.CommandExecuting })
.EnableSensitiveDataLogging();
How to logging with query tags
IQueryable<Product>? products = db.Products?
.TagWith("Products filtered by price and sorted.")
.Where(product => product.Cost > price)
.OrderByDescending(product => product.Cost);</Product>
How to pattern matching with Like
IQueryable<Product>? products = db.Products?
.Where(p => EF.Functions.Like(p.ProductName, $"%{input}%"));</Product>
How to generating a random number in queries
Product? p = db.Products?.FirstOrDefault(
p => p.ProductId == (int)(EF.Functions.Random() * rowCount));
How to defining global filters
modelBuilder.Entity<Product>()
.HasQueryFilter(p => !p.Discontinued)</Product>
How many loading patterns have with EF Core
- Eager loading: Load data early.
- Lazy loading: Load data automatically just before it is needed.
- Explicit loading: Load data manually.
How to statically import the System.Console class for all C# files?
<ItemGroup>
<Using></Using>
</ItemGroup>
Eager loading entities using the Include extension method
IQueryable<Category>? categories = db.Categories.Include(c => c.Products);</Category>
Enabling lazy loading
<PackageReference></PackageReference>
optionsBuilder.UseLazyLoadingProxies();
Explicit loading entities using the Load method
using Microsoft.EntityFrameworkCore.ChangeTracking;
CollectionEntry<Category, Product> products =
db.Entry(c).Collection(c2 => c2.Products);
if (!products.IsLoaded) products.Load();