### EF Core CLI version output Source: https://learn.microsoft.com/en-us/ef/core/cli/dotnet Example output showing the installed version of the EF Core CLI tools. ```text _/ __ ---==/ \\ ___ ___ |. \|\ | __|| __| | ) \\\ | _| | _| \_/ | //|\\ |___||_| / \\\/\\ Entity Framework Core .NET Command-line Tools 2.1.3-rtm-32065 ``` -------------------------------- ### Install SQL Server Provider Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server Commands to install the required NuGet package via .NET CLI or PowerShell. ```bash dotnet add package Microsoft.EntityFrameworkCore.SqlServer ``` ```powershell Install-Package Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Install EF Core Database Provider Source: https://learn.microsoft.com/en-us/ef/core/providers Commands to install a database provider package using .NET CLI or PowerShell. ```bash dotnet add package provider_package_name ``` ```powershell install-package provider_package_name ``` -------------------------------- ### Verify EF Core Tools Installation Source: https://learn.microsoft.com/en-us/ef/core/cli/powershell Run this command to confirm the tools are correctly installed and accessible. ```PowerShell Get-Help about_EntityFrameworkCore ``` -------------------------------- ### Install EF Core Templates Package Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/templates Install the necessary template package via the .NET CLI to enable custom scaffolding. ```bash dotnet new install Microsoft.EntityFrameworkCore.Templates ``` -------------------------------- ### Install .NET CLI EF Core tools globally Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/install Installs the dotnet-ef tool globally for use across all projects. ```bash dotnet tool install --global dotnet-ef ``` -------------------------------- ### Install the In-Memory Provider Source: https://learn.microsoft.com/en-us/ef/core/providers/in-memory Commands to add the Microsoft.EntityFrameworkCore.InMemory NuGet package to your project. ```bash dotnet add package Microsoft.EntityFrameworkCore.InMemory ``` ```powershell Install-Package Microsoft.EntityFrameworkCore.InMemory ``` -------------------------------- ### Execute Migration Bundle Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying Example of running the generated efbundle executable with a specific connection string. ```powershell .\efbundle.exe --connection 'Data Source=(local)\MSSQLSERVER;Initial Catalog=Blogging;User ID=myUsername;Password={;'$Credential;'here'}' ``` -------------------------------- ### Verify EF Core CLI installation Source: https://learn.microsoft.com/en-us/ef/core/cli/dotnet Runs the dotnet ef command to verify the tool is installed and check its version. ```bash dotnet ef ``` -------------------------------- ### Main Application Entry Point Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/diagnostic-listeners Example of initializing the diagnostic observer and performing database operations. ```C# public static async Task Main() { DiagnosticListener.AllListeners.Subscribe(new DiagnosticObserver()); using (var context = new BlogsContext()) { await context.Database.EnsureDeletedAsync(); await context.Database.EnsureCreatedAsync(); context.Add( new Blog { Name = "EF Blog", Posts = { new Post { Title = "EF Core 3.1!" }, new Post { Title = "EF Core 5.0!" } } }); await context.SaveChangesAsync(); } using (var context = new BlogsContext()) { var blog = await context.Blogs.Include(e => e.Posts).SingleAsync(); blog.Name = "EF Core Blog"; context.Remove(blog.Posts.First()); blog.Posts.Add(new Post { Title = "EF Core 6.0!" }); await context.SaveChangesAsync(); } ``` -------------------------------- ### Temporal table output example Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server/temporal-tables Example output showing the values of period columns for current rows. ```text Starting data: Employee Pinky Pie valid from 8/26/2021 4:38:58 PM to 12/31/9999 11:59:59 PM Employee Rainbow Dash valid from 8/26/2021 4:38:58 PM to 12/31/9999 11:59:59 PM Employee Fluttershy valid from 8/26/2021 4:38:58 PM to 12/31/9999 11:59:59 PM ``` -------------------------------- ### SQL output examples Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors Comparison of generated SQL when a query is tagged versus when it is not. ```sql -- Use hint: robust plan SELECT [b].[Id], [b].[Name] FROM [Blogs] AS [b] OPTION (ROBUST PLAN) ``` ```sql SELECT [b].[Id], [b].[Name] FROM [Blogs] AS [b] ``` -------------------------------- ### Example Command Execution Log Source: https://learn.microsoft.com/en-us/ef/core/performance/performance-diagnosis Sample output showing the execution time and SQL command details when LogLevel.Information is enabled. ```log info: 06/12/2020 09:12:36.117 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command) Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT [b].[Id], [b].[Name] FROM [Blogs] AS [b] WHERE [b].[Name] = N'foo' ``` -------------------------------- ### Define Blog and Post models Source: https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions Example entity models with string-based primary and foreign keys. ```C# public class Blog { public string Id { get; set; } public string Name { get; set; } public ICollection Posts { get; set; } } public class Post { public string Id { get; set; } public string Title { get; set; } public string Content { get; set; } public string BlogId { get; set; } public Blog Blog { get; set; } } ``` -------------------------------- ### Install EF Core tools via Package Manager Console Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/install Installs the Microsoft.EntityFrameworkCore.Tools package using the Visual Studio Package Manager Console. ```powershell Install-Package Microsoft.EntityFrameworkCore.Tools ``` -------------------------------- ### Generated OnConfiguring Method Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding Example of the scaffolded OnConfiguring method containing a connection string and a security warning. ```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. => optionsBuilder.UseSqlServer("Data Source=(LocalDb)\\MSSQLLocalDB;Database=AllTogetherNow"); ``` -------------------------------- ### dotnet-ef.json configuration properties Source: https://learn.microsoft.com/en-us/ef/core/cli/dotnet Example of a JSON configuration file containing optional properties for dotnet-ef. ```json { "project": "src/App.Infrastructure", "startupProject": "src/App.Api", "framework": "net11.0", "configuration": "Debug", "context": "AppDbContext", "runtime": "win-x64", "verbose": true, "noColor": false, "prefixOutput": false } ``` -------------------------------- ### Example dotnet-counters output Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/metrics Sample output showing the metrics reported by the Microsoft.EntityFrameworkCore counter provider. ```Console Press p to pause, r to resume, q to quit. Status: Running [Microsoft.EntityFrameworkCore] Active DbContexts 1 Execution Strategy Operation Failures (Count / 1 sec) 0 Execution Strategy Operation Failures (Total) 0 Optimistic Concurrency Failures (Count / 1 sec) 0 Optimistic Concurrency Failures (Total) 0 Queries (Count / 1 sec) 1 Queries (Total) 189 Query Cache Hit Rate (%) 100 SaveChanges (Count / 1 sec) 0 SaveChanges (Total) 0 ``` -------------------------------- ### Example log output Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors Sample output generated when a property change is logged by the entity. ```text info: CustomersLogger[1] Updating phone number for 'Alice' from '+1 515 555 0123' to '+1 515 555 0125'. ``` -------------------------------- ### Install EF Core Cosmos DB Provider Source: https://learn.microsoft.com/en-us/ef/core/providers/cosmos Use these commands to add the Microsoft.EntityFrameworkCore.Cosmos NuGet package to your project. ```dotnet dotnet add package Microsoft.EntityFrameworkCore.Cosmos ``` ```powershell Install-Package Microsoft.EntityFrameworkCore.Cosmos ``` -------------------------------- ### Generate SQL script for migrations Source: https://learn.microsoft.com/en-us/ef/core/cli/dotnet Examples of generating SQL scripts from migrations using the .NET CLI. ```bash dotnet ef migrations script 0 InitialCreate ``` ```bash dotnet ef migrations script 20180904195021_InitialCreate ``` -------------------------------- ### LINQ queries for null comparison Source: https://learn.microsoft.com/en-us/ef/core/querying/null-comparisons Example LINQ queries demonstrating various nullability scenarios. ```csharp var query1 = context.Entities.Where(e => e.Id == e.Int); var query2 = context.Entities.Where(e => e.Id == e.NullableInt); var query3 = context.Entities.Where(e => e.Id != e.NullableInt); var query4 = context.Entities.Where(e => e.String1 == e.String2); var query5 = context.Entities.Where(e => e.String1 != e.String2); ``` -------------------------------- ### Example database schema Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding SQL definition for tables used to demonstrate naming convention changes. ```sql CREATE TABLE [BLOGS] ( [ID] int NOT NULL IDENTITY, [Blog_Name] nvarchar(max) NOT NULL, CONSTRAINT [PK_Blogs] PRIMARY KEY ([ID])); CREATE TABLE [posts] ( [id] int NOT NULL IDENTITY, [postTitle] nvarchar(max) NOT NULL, [post content] nvarchar(max) NOT NULL, [1 PublishedON] datetime2 NOT NULL, [2 DeletedON] datetime2 NULL, [BlogID] int NOT NULL, CONSTRAINT [PK_Posts] PRIMARY KEY ([id]), CONSTRAINT [FK_Posts_Blogs_BlogId] FOREIGN KEY ([BlogID]) REFERENCES [Blogs] ([ID]) ON DELETE CASCADE); ``` -------------------------------- ### Install EF Core SQLite Provider Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app Commands to add the SQLite database provider package to your project. ```bash dotnet add package Microsoft.EntityFrameworkCore.Sqlite ``` ```powershell Install-Package Microsoft.EntityFrameworkCore.Sqlite ``` -------------------------------- ### Generate SQL script from blank to latest Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying Generates a SQL script starting from a blank database up to the latest migration. ```bash dotnet ef migrations script ``` ```powershell Script-Migration ``` -------------------------------- ### Define connection string in appsettings.json Source: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings Example structure for storing a connection string within the application configuration file. ```json { "ConnectionStrings": { "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;" }, } ``` -------------------------------- ### Install SpatiaLite via Package Manager Source: https://learn.microsoft.com/en-us/ef/core/providers/sqlite/spatial Commands to install the native mod_spatialite library on Debian/Ubuntu and macOS systems. ```bash # Debian/Ubuntu apt-get install libsqlite3-mod-spatialite # macOS brew install libspatialite ``` -------------------------------- ### Create Database via CLI and PMC Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app Commands to install necessary EF Core tools and apply migrations to create the database. ```bash dotnet tool install --global dotnet-ef dotnet add package Microsoft.EntityFrameworkCore.Design dotnet ef migrations add InitialCreate dotnet ef database update ``` ```powershell Install-Package Microsoft.EntityFrameworkCore.Tools Add-Migration InitialCreate Update-Database ``` -------------------------------- ### Create a new console project using .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app Initializes a new .NET console project and navigates into the project directory. ```bash dotnet new console -o EFGetStarted cd EFGetStarted ``` -------------------------------- ### Create and apply a migration in one step Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/managing Use the --add option to compile and apply a migration in a single command. ```shell dotnet ef database update InitialCreate --add ``` ```shell dotnet ef database update AddProducts --add --output-dir Migrations/Products --namespace MyApp.Migrations ``` ```powershell Update-Database -Migration InitialCreate -Add ``` -------------------------------- ### ShortView Output Example Source: https://learn.microsoft.com/en-us/ef/core/change-tracking/debug-views The resulting output from the short debug view showing entity states, keys, and relationships. ```text Blog {Id: 1} Modified AK {AssetsId: ed727978-1ffe-4709-baee-73913e8e44a0} Blog {Id: 2} Unchanged AK {AssetsId: 3a54b880-2b9d-486b-9403-dc2e52d36d65} BlogAssets {Id: 3a54b880-2b9d-486b-9403-dc2e52d36d65} Unchanged FK {Id: 3a54b880-2b9d-486b-9403-dc2e52d36d65} BlogAssets {Id: ed727978-1ffe-4709-baee-73913e8e44a0} Unchanged FK {Id: ed727978-1ffe-4709-baee-73913e8e44a0} Post {Id: -2147482643} Added FK {BlogId: 1} Post {Id: 1} Unchanged FK {BlogId: 1} Post {Id: 2} Unchanged FK {BlogId: 1} Post {Id: 3} Unchanged FK {BlogId: 2} Post {Id: 4} Deleted FK {BlogId: 2} PostTag (Dictionary) {PostsId: 1, TagsId: 1} Unchanged FK {PostsId: 1} FK {TagsId: 1} PostTag (Dictionary) {PostsId: 1, TagsId: 3} Unchanged FK {PostsId: 1} FK {TagsId: 3} PostTag (Dictionary) {PostsId: 2, TagsId: 1} Unchanged FK {PostsId: 2} FK {TagsId: 1} PostTag (Dictionary) {PostsId: 3, TagsId: 2} Unchanged FK {PostsId: 3} FK {TagsId: 2} PostTag (Dictionary) {PostsId: 4, TagsId: 2} Deleted FK {PostsId: 4} FK {TagsId: 2} Tag {Id: 1} Unchanged Tag {Id: 2} Unchanged Tag {Id: 3} Unchanged ``` -------------------------------- ### Configure GUID key generation Source: https://learn.microsoft.com/en-us/ef/core/providers/cosmos/modeling Configures the entity key to use a GUID value generator for unique, random values at the client. ```csharp modelBuilder.Entity().Property(b => b.Id).HasValueGenerator(); ``` -------------------------------- ### Configure Sequential GUIDs for Non-Key Properties Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server/value-generation Use the SequentialGuidValueGenerator to ensure non-key properties receive sequential GUIDs generated on the client. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().Property(b => b.Guid).HasValueGenerator(typeof(SequentialGuidValueGenerator)); } ``` -------------------------------- ### Install EF Core SQL Server provider via .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/install Use this command in the terminal to add the SQL Server provider package to your project. ```bash dotnet add package Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Configure one-to-one starting from entity without navigation Source: https://learn.microsoft.com/en-us/ef/core/modeling/relationships/one-to-one Uses the generic HasOne method to configure the relationship when starting from the entity that lacks the navigation property. ```C# protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasOne() .WithOne(e => e.Blog) .HasForeignKey(e => e.BlogId) .IsRequired(); } ``` -------------------------------- ### Install EF Core Tasks package Source: https://learn.microsoft.com/en-us/ef/core/cli/msbuild Use the .NET CLI to add the required NuGet package for MSBuild integration. ```bash dotnet add package Microsoft.EntityFrameworkCore.Tasks ``` -------------------------------- ### Configure Relationship Starting from Dependent Entity Source: https://learn.microsoft.com/en-us/ef/core/modeling/relationships/one-to-one Configures the relationship starting from the entity that lacks a navigation property, requiring an explicit generic type in HasOne. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasOne() .WithOne(e => e.Header) .HasForeignKey(e => e.BlogId) .IsRequired(); } ``` -------------------------------- ### Create a database view Source: https://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types SQL command to create a view for aggregating post counts per blog. ```csharp await db.Database.ExecuteSqlRawAsync( @"CREATE VIEW View_BlogPostCounts AS SELECT b.Name, Count(p.PostId) as PostCount FROM Blogs b JOIN Posts p on p.BlogId = b.BlogId GROUP BY b.Name"); ``` -------------------------------- ### Configure one-to-many starting from principal Source: https://learn.microsoft.com/en-us/ef/core/modeling/relationships/one-to-many Configures the relationship starting from the principal entity, using HasMany() to specify the target type when no navigation exists. ```C# protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasMany() .WithOne(e => e.Blog) .HasForeignKey(e => e.BlogId) .IsRequired(); } ``` -------------------------------- ### Create a migration bundle Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying Generates an executable file containing all pending migrations. ```bash PS C:\local\AllTogetherNow\SixOh> dotnet ef migrations bundle Build started... Build succeeded. Building bundle... Done. Migrations Bundle: C:\local\AllTogetherNow\SixOh\efbundle.exe PS C:\local\AllTogetherNow\SixOh> ``` -------------------------------- ### Interceptor output Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors Expected console output from the retrieval example. ```text Customer 'Alice' was retrieved at '9/22/2022 5:25:54 PM' ``` -------------------------------- ### Get-DbContext Source: https://learn.microsoft.com/en-us/ef/core/cli/powershell Lists and gets information about available DbContext types. ```APIDOC ## Get-DbContext ### Description Lists and gets information about available DbContext types. ``` -------------------------------- ### Implement IHasIntKey on entity Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors Example entity class implementation of the IHasIntKey interface. ```csharp public class Customer : IHasIntKey { public int Id { get; set; } public string Name { get; set; } = null!; public string? City { get; set; } public string? PhoneNumber { get; set; } } ``` -------------------------------- ### Implement the repository for production Source: https://learn.microsoft.com/en-us/ef/core/testing/testing-without-the-database Create a concrete implementation of the repository that wraps the EF Core context. ```C# public class BloggingRepository : IBloggingRepository { private readonly BloggingContext _context; public BloggingRepository(BloggingContext context) => _context = context; public async Task GetBlogByNameAsync(string name) => await _context.Blogs.FirstOrDefaultAsync(b => b.Name == name); // Other code... } ``` -------------------------------- ### Save and Query Data Source: https://learn.microsoft.com/en-us/ef/core/providers/cosmos Demonstrates creating the database, adding an entity, and querying it back using standard EF Core patterns. ```csharp using (var context = new OrderContext()) { await context.Database.EnsureDeletedAsync(); await context.Database.EnsureCreatedAsync(); context.Add( new Order { Id = 1, ShippingAddress = new StreetAddress { City = "London", Street = "221 B Baker St" }, PartitionKey = "1" }); await context.SaveChangesAsync(); } using (var context = new OrderContext()) { var order = await context.Orders.FirstAsync(); Console.WriteLine($"First order will ship to: {order.ShippingAddress.Street}, {order.ShippingAddress.City}"); Console.WriteLine(); } ``` -------------------------------- ### Register DiagnosticObserver Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/diagnostic-listeners Register the observer globally to start listening for diagnostic events. ```C# DiagnosticListener.AllListeners.Subscribe(new DiagnosticObserver()); ``` -------------------------------- ### Add migrations for multiple context types Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/providers Use the CLI or PowerShell to specify the context and output directory for each provider's migration set. ```bash dotnet ef migrations add InitialCreate --context BlogContext --output-dir Migrations/SqlServerMigrations dotnet ef migrations add InitialCreate --context SqliteBlogContext --output-dir Migrations/SqliteMigrations ``` ```powershell Add-Migration InitialCreate -Context BlogContext -OutputDir Migrations\SqlServerMigrations Add-Migration InitialCreate -Context SqliteBlogContext -OutputDir Migrations\SqliteMigrations ``` -------------------------------- ### Configure UseSeeding and UseAsyncSeeding Source: https://learn.microsoft.com/en-us/ef/core/modeling/data-seeding Demonstrates setting up database seeding logic within the DbContext options configuration. These methods are triggered by EnsureCreated, Migrate, and database update commands. ```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFDataSeeding;Trusted_Connection=True;ConnectRetryCount=0") .UseSeeding((context, _) => { var testBlog = context.Set().FirstOrDefault(b => b.Url == "http://test.com"); if (testBlog == null) { context.Set().Add(new Blog { Url = "http://test.com" }); context.SaveChanges(); } }) .UseAsyncSeeding(async (context, _, cancellationToken) => { var testBlog = await context.Set().FirstOrDefaultAsync(b => b.Url == "http://test.com", cancellationToken); if (testBlog == null) { context.Set().Add(new Blog { Url = "http://test.com" }); await context.SaveChangesAsync(cancellationToken); } }); ``` -------------------------------- ### Define a mutable list property Source: https://learn.microsoft.com/en-us/ef/core/modeling/value-comparers Example of a property using a mutable List type. ```csharp public List MyListProperty { get; set; } ``` -------------------------------- ### Query entity with interceptor Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors Example usage showing the retrieved property populated after querying. ```csharp await using (var context = new CustomerContext()) { var customer = await context.Customers.SingleAsync(e => e.Name == "Alice"); Console.WriteLine($"Customer '{customer.Name}' was retrieved at '{customer.Retrieved.ToLocalTime()}'"); } ``` -------------------------------- ### Create initial migration Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations Commands to generate the first migration for the database schema. ```bash dotnet ef migrations add InitialCreate ``` ```powershell Add-Migration InitialCreate ``` -------------------------------- ### Display historical data output Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server/temporal-tables Example output showing the historical state of an entity over time. ```none Historical data for Rainbow Dash: Employee Rainbow Dash was 'Ponyville weather patrol' from 8/26/2021 4:38:58 PM to 8/26/2021 4:40:29 PM Employee Rainbow Dash was 'Wonderbolt Trainee' from 8/26/2021 4:40:29 PM to 8/26/2021 4:41:59 PM Employee Rainbow Dash was 'Wonderbolt Reservist' from 8/26/2021 4:41:59 PM to 8/26/2021 4:43:29 PM Employee Rainbow Dash was 'Wonderbolt' from 8/26/2021 4:43:29 PM to 8/26/2021 4:44:59 PM Employee Rainbow Dash was 'Wonderbolt Trainee' from 8/26/2021 4:44:59 PM to 12/31/9999 11:59:59 PM ``` -------------------------------- ### Reference Migrations Project Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/projects Add a project reference to the migrations library in the startup project's project file. ```XML ``` -------------------------------- ### Generated SQL for JSON Index Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server Example of the SQL command generated by migrations for a JSON index. ```sql CREATE JSON INDEX [IX_Customers_Contact_Address_City] ON [Customers]([Contact]) FOR (N'$.Address.City'); ``` -------------------------------- ### View generated SQL query execution Source: https://learn.microsoft.com/en-us/ef/core/providers/cosmos/querying Example of the underlying SQL query generated by the provider. ```sql SELECT VALUE s FROM ( SELECT VALUE c FROM root c WHERE c.Angle1 <= @p0 ) s ``` -------------------------------- ### Register repository in dependency injection Source: https://learn.microsoft.com/en-us/ef/core/testing/testing-without-the-database Configure the repository service in the application's startup configuration. ```C# services.AddScoped(); ``` -------------------------------- ### Create a document with EF Core Source: https://learn.microsoft.com/en-us/ef/core/providers/cosmos/planetary-docs-sample Standard approach for adding a document to the database context. ```C# context.Add(document); await context.SaveChangesAsync(); ``` -------------------------------- ### Define inheritance hierarchy classes Source: https://learn.microsoft.com/en-us/ef/core/modeling/table-splitting Base class and derived classes for inheritance mapping examples. ```csharp public abstract class Animal { public int Id { get; set; } public string Breed { get; set; } = null!; } public class Cat : Animal { public string? EducationalLevel { get; set; } } public class Dog : Animal { public string? FavoriteToy { get; set; } } ``` -------------------------------- ### Define a custom Currency struct Source: https://learn.microsoft.com/en-us/ef/core/modeling/bulk-configuration A custom value type used as an example for bulk configuration. ```csharp public readonly struct Currency { public Currency(decimal amount) => Amount = amount; public decimal Amount { get; } public override string ToString() => $"${Amount}"; } ``` -------------------------------- ### Configure SQL Server Provider Source: https://learn.microsoft.com/en-us/ef/core/providers Example of configuring the SQL Server provider within the OnConfiguring method using a connection string. ```csharp optionsBuilder.UseSqlServer( @"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;"); ``` -------------------------------- ### Generated TPC Database Schema Source: https://learn.microsoft.com/en-us/ef/core/modeling/inheritance Example SQL schema generated for a TPC mapping configuration. ```sql CREATE TABLE [Blogs] ( [BlogId] int NOT NULL DEFAULT (NEXT VALUE FOR [BlogSequence]), [Url] nvarchar(max) NULL, CONSTRAINT [PK_Blogs] PRIMARY KEY ([BlogId]) ); CREATE TABLE [RssBlogs] ( [BlogId] int NOT NULL DEFAULT (NEXT VALUE FOR [BlogSequence]), [Url] nvarchar(max) NULL, [RssUrl] nvarchar(max) NULL, CONSTRAINT [PK_RssBlogs] PRIMARY KEY ([BlogId]) ); ``` -------------------------------- ### Generate Migration Bundles Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying Commands to create migration bundles using .NET CLI or PowerShell, including options for self-contained deployment. ```bash dotnet ef migrations bundle ``` ```bash dotnet ef migrations bundle --self-contained -r linux-x64 ``` ```powershell Bundle-Migration ``` ```powershell Bundle-Migration -SelfContained -TargetRuntime linux-x64 ``` -------------------------------- ### Scaffold Data Annotations configuration Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding Example of how Data Annotations configure entity properties during scaffolding. ```csharp [Required] [StringLength(160)] public string Title { get; set; } ``` -------------------------------- ### Execute a migration bundle Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying Runs the generated executable to apply pending migrations to the database. ```bash PS C:\local\AllTogetherNow\SixOh> .\efbundle.exe Applying migration '20210903083845_MyMigration'. Done. PS C:\local\AllTogetherNow\SixOh> ``` -------------------------------- ### Scaffold Fluent API configuration Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding Example of how the Fluent API configures entity properties during scaffolding. ```csharp entity.Property(e => e.Title) .IsRequired() .HasMaxLength(160); ``` -------------------------------- ### Invoke ef.dll via .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/miscellaneous/internals/tools Executes the ef.dll assembly using the startup project's dependency and runtime configuration files. ```bash dotnet exec ef.dll --depsfile startupProject.deps.json --runtimeconfig startupProject.runtimeconfig.json ``` -------------------------------- ### Setup and seed an in-memory database in a test constructor Source: https://learn.microsoft.com/en-us/ef/core/testing/testing-without-the-database Initializes DbContextOptions with the in-memory provider and seeds initial data before each test. ```C# public InMemoryBloggingControllerTest() { _contextOptions = new DbContextOptionsBuilder() .UseInMemoryDatabase("BloggingControllerTest") .ConfigureWarnings(b => b.Ignore(InMemoryEventId.TransactionIgnoredWarning)) .Options; using var context = new BloggingContext(_contextOptions); context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.AddRange( new Blog { Name = "Blog1", Url = "http://blog1.com" }, new Blog { Name = "Blog2", Url = "http://blog2.com" }); context.SaveChanges(); } ``` -------------------------------- ### Enable NativeAOT in Project File Source: https://learn.microsoft.com/en-us/ef/core/performance/nativeaot-and-precompiled-queries Add the PublishAot property to your project file to enable NativeAOT publishing. ```xml true ``` -------------------------------- ### Change tracker debug output Source: https://learn.microsoft.com/en-us/ef/core/change-tracking Example output showing entity states and modified properties. ```text Blog {Id: 1} Modified Id: 1 PK Name: '.NET Blog (Updated!)' Modified Originally '.NET Blog' Posts: [{Id: 1}, {Id: 2}, {Id: 3}] Post {Id: 1} Unchanged Id: 1 PK BlogId: 1 FK Content: 'Announcing the release of EF Core 5.0, a full featured cross...' Title: 'Announcing the Release of EF Core 5.0' Blog: {Id: 1} Post {Id: 2} Modified Id: 2 PK BlogId: 1 FK Content: 'F# 5 is the latest version of F#, the functional programming...' Title: 'Announcing F# 5.0' Modified Originally 'Announcing F# 5' Blog: {Id: 1} ``` -------------------------------- ### Attach a graph of entities with generated keys Source: https://learn.microsoft.com/en-us/ef/core/change-tracking/explicit-tracking Demonstrates attaching a blog and its posts where some posts have existing IDs and one does not. ```csharp context.Attach( new Blog { Id = 1, Name = ".NET Blog", Posts = { new Post { Id = 1, Title = "Announcing the Release of EF Core 5.0", Content = "Announcing the release of EF Core 5.0, a full featured cross-platform..." }, new Post { Id = 2, Title = "Announcing F# 5", Content = "F# 5 is the latest version of F#, the functional programming language..." }, new Post { Title = "Announcing .NET 5.0", Content = ".NET 5.0 includes many enhancements, including single file applications, more..." }, } }); ``` -------------------------------- ### Apply new migrations from a bundle Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying Executes the updated bundle to apply the newly added migrations. ```bash PS C:\local\AllTogetherNow\SixOh> .\efbundle.exe Applying migration '20210903084526_SecondMigration'. Applying migration '20210903084538_Number3'. Done. PS C:\local\AllTogetherNow\SixOh> ``` -------------------------------- ### Query and update entities Source: https://learn.microsoft.com/en-us/ef/core/change-tracking Example of querying entities, modifying properties, and persisting changes to the database. ```csharp using var context = new BlogsContext(); var blog = await context.Blogs.Include(e => e.Posts).FirstAsync(e => e.Name == ".NET Blog"); blog.Name = ".NET Blog (Updated!)"; await foreach (var post in blog.Posts.AsQueryable().Where(e => !e.Title.Contains("5.0")).AsAsyncEnumerable()) { post.Title = post.Title.Replace("5", "5.0"); } await context.SaveChangesAsync(); ``` -------------------------------- ### Get the direct ancestor of an entity Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server/hierarchyid Uses GetAncestor to retrieve the parent node of a specific entity. ```C# async Task FindDirectAncestor(string name) => await context.Halflings .SingleOrDefaultAsync( ancestor => ancestor.PathFromPatriarch == context.Halflings .Single(descendent => descendent.Name == name).PathFromPatriarch .GetAncestor(1)); ``` ```SQL SELECT TOP(2) [h].[Id], [h].[Name], [h].[PathFromPatriarch], [h].[YearOfBirth] FROM [Halflings] AS [h] WHERE [h].[PathFromPatriarch] = ( SELECT TOP(1) [h0].[PathFromPatriarch] FROM [Halflings] AS [h0] WHERE [h0].[Name] = @__name_0).GetAncestor(1) ``` -------------------------------- ### Run application with .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app Executes the .NET application from the command line. ```bash dotnet run ``` -------------------------------- ### Implement Data Interaction in MainWindow.xaml.cs Source: https://learn.microsoft.com/en-us/ef/core/get-started/wpf Manage the ProductContext lifecycle and handle data loading and saving events in the code-behind. ```C# using Microsoft.EntityFrameworkCore; using System.ComponentModel; using System.Windows; using System.Windows.Data; namespace GetStartedWPF { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { private readonly ProductContext _context = new ProductContext(); private CollectionViewSource categoryViewSource; public MainWindow() { InitializeComponent(); categoryViewSource = (CollectionViewSource)FindResource(nameof(categoryViewSource)); } private void Window_Loaded(object sender, RoutedEventArgs e) { // this is for demo purposes only, to make it easier // to get up and running _context.Database.EnsureCreated(); // load the entities into EF Core _context.Categories.Load(); // bind to the source categoryViewSource.Source = _context.Categories.Local.ToObservableCollection(); } private void Button_Click(object sender, RoutedEventArgs e) { // all changes are automatically tracked, including // deletes! _context.SaveChanges(); // this forces the grid to refresh to latest values categoryDataGrid.Items.Refresh(); productsDataGrid.Items.Refresh(); } protected override void OnClosing(CancelEventArgs e) { // clean up database connections _context.Dispose(); base.OnClosing(e); } } } ``` -------------------------------- ### Get entities at a specific level Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server/hierarchyid Uses GetLevel to filter entities based on their depth in the hierarchy. ```C# var generation = await context.Halflings.Where(halfling => halfling.PathFromPatriarch.GetLevel() == level).ToListAsync(); ``` ```SQL SELECT [h].[Id], [h].[Name], [h].[PathFromPatriarch], [h].[YearOfBirth] FROM [Halflings] AS [h] WHERE [h].[PathFromPatriarch].GetLevel() = @__level_0 ``` -------------------------------- ### Define entities for UDF mapping Source: https://learn.microsoft.com/en-us/ef/core/querying/user-defined-function-mapping Example entity classes representing a blog, post, and comment structure. ```csharp public class Blog { public int BlogId { get; set; } public string Url { get; set; } public int? Rating { get; set; } public List Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int Rating { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } public List Comments { get; set; } } public class Comment { public int CommentId { get; set; } public string Text { get; set; } public int Likes { get; set; } public int PostId { get; set; } public Post Post { get; set; } } ``` -------------------------------- ### Scaffold using a connection string from user secrets Source: https://learn.microsoft.com/en-us/ef/core/cli/dotnet Demonstrates setting a connection string via the Secret Manager tool and referencing it in the scaffold command. ```bash dotnet user-secrets set ConnectionStrings:Blogging "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Blogging" dotnet ef dbcontext scaffold Name=ConnectionStrings:Blogging Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Define Principal and Dependent Entities Source: https://learn.microsoft.com/en-us/ef/core/saving/cascade-delete Example model showing a one-to-many relationship where Post is dependent on Blog. ```csharp public class Blog { public int Id { get; set; } public string Name { get; set; } public IList Posts { get; } = new List(); } public class Post { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } ``` -------------------------------- ### Generated SQL for LINQ Composition Source: https://learn.microsoft.com/en-us/ef/core/querying/sql-queries The resulting SQL generated by the EF Core LINQ composition example. ```sql SELECT [b].[BlogId], [b].[OwnerId], [b].[Rating], [b].[Url] FROM ( SELECT * FROM dbo.SearchBlogs(@p0) ) AS [b] WHERE [b].[Rating] > 3 ORDER BY [b].[Rating] DESC ``` -------------------------------- ### Configure NetTopologySuite for SQL Server Source: https://learn.microsoft.com/en-us/ef/core/modeling/spatial Enable spatial data mapping by calling UseNetTopologySuite within the provider's options builder. ```csharp options.UseSqlServer( @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=WideWorldImporters;ConnectRetryCount=0", x => x.UseNetTopologySuite()); ``` -------------------------------- ### Attempting dynamic column filtering Source: https://learn.microsoft.com/en-us/ef/core/querying/sql-queries An example of an invalid approach to parameterizing column names, which is not supported by databases. ```csharp var propertyName = "User"; var propertyValue = "johndoe"; var blogs = await context.Blogs .FromSql($"SELECT * FROM [Blogs] WHERE {propertyName} = {propertyValue}") .ToListAsync(); ```