### Install EF Core Tools Source: https://learn.microsoft.com/en-us/ef/core/cli/powershell Installs the Microsoft.EntityFrameworkCore.Tools package using PowerShell. ```powershell Install-Package Microsoft.EntityFrameworkCore.Tools ``` -------------------------------- ### Install SQL Server EF Core Provider (.NET CLI) Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server Installs the Microsoft.EntityFrameworkCore.SqlServer NuGet package using the .NET CLI. ```csharp dotnet add package Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Install EF Core Tools and Create Database (.NET CLI) Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app Installs the EF Core tools and design package, then scaffolds and applies the initial database migration. ```bash dotnet tool install --global dotnet-ef dotnet add package Microsoft.EntityFrameworkCore.Design dotnet ef migrations add InitialCreate dotnet ef database update ``` -------------------------------- ### Install EF Core Tools and Create Database (Package Manager Console) Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app Installs the EF Core tools via PMC, then scaffolds and applies the initial database migration. ```powershell Install-Package Microsoft.EntityFrameworkCore.Tools Add-Migration InitialCreate Update-Database ``` -------------------------------- ### Install SQL Server EF Core Provider (PowerShell) Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server Installs the Microsoft.EntityFrameworkCore.SqlServer NuGet package using PowerShell. ```powershell Install-Package Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Verify EF Core CLI Tools Installation Source: https://learn.microsoft.com/en-us/ef/core/cli/dotnet Runs the EF Core CLI tool to verify that it is installed correctly and displays its version information. ```bash dotnet ef ``` -------------------------------- ### Install EF Core Cosmos Provider using PowerShell Source: https://learn.microsoft.com/en-us/ef/core/providers/cosmos Use PowerShell to install the Microsoft.EntityFrameworkCore.Cosmos NuGet package. ```powershell Install-Package Microsoft.EntityFrameworkCore.Cosmos ``` -------------------------------- ### Install Microsoft.EntityFrameworkCore.InMemory using PowerShell Source: https://learn.microsoft.com/en-us/ef/core/providers/in-memory Use PowerShell to install the Microsoft.EntityFrameworkCore.InMemory NuGet package. This is an alternative to the .NET CLI for package management. ```powershell Install-Package Microsoft.EntityFrameworkCore.InMemory ``` -------------------------------- ### Install Microsoft.EntityFrameworkCore.SqlServer.HierarchyId Package (Package Manager Console) Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server/hierarchyid Install the required NuGet package using the Package Manager Console in Visual Studio. ```powershell Install-Package Microsoft.EntityFrameworkCore.SqlServer.HierarchyId ``` -------------------------------- ### Example output Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors This is the expected output when querying a customer and displaying their retrieval time. ```text Customer 'Alice' was retrieved at '9/22/2022 5:25:54 PM' ``` -------------------------------- ### Install Microsoft.EntityFrameworkCore.InMemory using .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/providers/in-memory Use the .NET CLI to add the Microsoft.EntityFrameworkCore.InMemory NuGet package to your project. This command installs the necessary package for using the in-memory database provider. ```bash dotnet add package Microsoft.EntityFrameworkCore.InMemory ``` -------------------------------- ### Configure Sequence Settings - C# Source: https://learn.microsoft.com/en-us/ef/core/modeling/sequences Configure additional sequence properties such as schema, starting value, and increment. This example sets up a sequence in the 'shared' schema, starting at 1000 and incrementing by 5. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasSequence("OrderNumbers", schema: "shared") .StartsAt(1000) .IncrementsBy(5); } ``` -------------------------------- ### Example Database Updates (SQLite) Source: https://learn.microsoft.com/en-us/ef/core/change-tracking Illustrates the SQL commands executed to update the database after changes are detected and saved. ```sql -- Executed DbCommand (0ms) [Parameters=[@p1='1' (DbType = String), @p0='.NET Blog (Updated!)' (Size = 20)], CommandType='Text', CommandTimeout='30'] UPDATE "Blogs" SET "Name" = @p0 WHERE "Id" = @p1; SELECT changes(); -- Executed DbCommand (0ms) [Parameters=[@p1='2' (DbType = String), @p0='Announcing F# 5.0' (Size = 17)], CommandType='Text', CommandTimeout='30'] UPDATE "Posts" SET "Title" = @p0 WHERE "Id" = @p1; SELECT changes(); ``` -------------------------------- ### Install EF Core Cosmos Provider using .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/providers/cosmos Use the .NET CLI to add the Microsoft.EntityFrameworkCore.Cosmos NuGet package to your project. ```bash dotnet add package Microsoft.EntityFrameworkCore.Cosmos ``` -------------------------------- ### Install .NET CLI Tools Globally Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/install Installs the `dotnet ef` global tool, which is the recommended approach for most developers. This tool is used for EF Core-related tasks via the command line. ```.NET CLI dotnet tool install --global dotnet-ef ``` -------------------------------- ### Verify EF Core Tools Installation Source: https://learn.microsoft.com/en-us/ef/core/cli/powershell Checks if the Entity Framework Core tools are installed by displaying help information. ```powershell Get-Help about_EntityFrameworkCore ``` -------------------------------- ### Install EF Core SQL Server Provider using Package Manager Console Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/install Use the Package Manager Console in Visual Studio to install the EF Core SQL Server provider. Use `Update-Package` to update and the `-Version` modifier to specify a version. ```powershell Install-Package Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Install EF Core Template Package Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/templates Install the EF Core template package using the .NET CLI. This package provides the default templates for reverse engineering. ```.NET CLI dotnet new install Microsoft.EntityFrameworkCore.Templates ``` -------------------------------- ### Install Package Manager Console Tools Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/install Installs the `Microsoft.EntityFrameworkCore.Tools` package for use within Visual Studio's Package Manager Console. This enables commands like `Add-Migration` and `Update-Database`. ```PowerShell Install-Package Microsoft.EntityFrameworkCore.Tools ``` -------------------------------- ### Connection String in appsettings.json Source: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings Example of a connection string stored in the appsettings.json file for a local database. ```json { "ConnectionStrings": { "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;" }, } ``` -------------------------------- ### Usage Example: Saving and Querying Entities Source: https://learn.microsoft.com/en-us/ef/core/modeling/table-splitting Demonstrates how to add, save, and query entities configured with table splitting. The context handles the mapping automatically. ```csharp using (var context = new TableSplittingContext()) { await context.Database.EnsureDeletedAsync(); await context.Database.EnsureCreatedAsync(); context.Add( new Order { Status = OrderStatus.Pending, DetailedOrder = new DetailedOrder { Status = OrderStatus.Pending, ShippingAddress = "221 B Baker St, London", BillingAddress = "11 Wall Street, New York" } }); await context.SaveChangesAsync(); } using (var context = new TableSplittingContext()) { var pendingCount = await context.Orders.CountAsync(o => o.Status == OrderStatus.Pending); Console.WriteLine($"Current number of pending orders: {pendingCount}"); } using (var context = new TableSplittingContext()) { var order = await context.DetailedOrders.FirstAsync(o => o.Status == OrderStatus.Pending); Console.WriteLine($"First pending order will ship to: {order.ShippingAddress}"); } ``` -------------------------------- ### Create a LoggerFactory Instance Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/extensions-logging Create a static LoggerFactory instance to be used globally for logging. This example adds the console logger provider. ```csharp public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); }); ``` -------------------------------- ### Query the Database View Source: https://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types Example of querying the `BlogPostCounts` DbSet and iterating through the results to display blog post counts. ```csharp var postCounts = await db.BlogPostCounts.ToListAsync(); foreach (var postCount in postCounts) { Console.WriteLine($"{postCount.BlogName} has {postCount.PostCount} posts."); Console.WriteLine(); } ``` -------------------------------- ### Install EF Core SQLite Package (Package Manager Console) Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app Use the Package Manager Console in Visual Studio to install the Microsoft.EntityFrameworkCore.Sqlite package. This command is equivalent to the .NET CLI command. ```PowerShell Install-Package Microsoft.EntityFrameworkCore.Sqlite ``` -------------------------------- ### Custom Operation Example Usage Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/operations This is how you would call a custom migration operation to create a user. ```csharp migrationBuilder.CreateUser("SQLUser1", "Password"); ``` -------------------------------- ### Rewriting Dynamic Query for Precompilation Source: https://learn.microsoft.com/en-us/ef/core/performance/nativeaot-and-precompiled-queries This example shows how a dynamic query can be rewritten into two distinct, statically analyzable queries, making them suitable for precompilation. ```csharp IAsyncEnumerable GetBlogs(BlogContext context, bool applyFilter) => applyFilter ? context.Blogs.OrderBy(b => b.Id).Where(b => b.Name != "foo").AsAsyncEnumerable() : context.Blogs.OrderBy(b => b.Id).AsAsyncEnumerable(); ``` -------------------------------- ### Add a new blog with an explicit ID Source: https://learn.microsoft.com/en-us/ef/core/change-tracking/explicit-tracking Use `context.Add()` to start tracking a new entity with an explicitly defined key. The entity is initially in the 'Added' state. ```csharp context.Add( new Blog { Id = 1, Name = ".NET Blog", }); ``` -------------------------------- ### Get Entity State Source: https://learn.microsoft.com/en-us/ef/core/change-tracking/entity-entries Access the current EntityState of a tracked entity using the State property of its EntityEntry. You can also set the state, for example, to mark an unchanged entity as modified. ```csharp var currentState = context.Entry(blog).State; if (currentState == EntityState.Unchanged) { context.Entry(blog).State = EntityState.Modified; } ``` -------------------------------- ### Apply migrations and create database using .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations Execute this .NET CLI command to apply all pending migrations and create the database schema. ```bash dotnet ef database update ``` -------------------------------- ### In-Memory Database Setup and Seeding Source: https://learn.microsoft.com/en-us/ef/core/testing/testing-without-the-database This constructor sets up and seeds an in-memory database for testing. It configures the database, ensures it's deleted and created, and adds initial blog data. Transactions are ignored by default. ```csharp 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(); } ``` -------------------------------- ### Create and Use Design-Time Services Source: https://learn.microsoft.com/en-us/ef/core/cli/services Demonstrates how to set up a service provider and use it to scaffold and save a new migration. Requires EF Core tooling. ```csharp using var db = new MyDbContext(); // Create design-time services var serviceCollection = new ServiceCollection(); serviceCollection.AddDbContextDesignTimeServices(db); var provider = db.GetService().Name; var providerAssembly = Assembly.Load(new AssemblyName(provider)); var providerServicesAttribute = providerAssembly.GetCustomAttribute(); var designTimeServicesType = providerAssembly.GetType(providerServicesAttribute.TypeName, throwOnError: true); ((IDesignTimeServices)Activator.CreateInstance(designTimeServicesType)!).ConfigureDesignTimeServices(serviceCollection); serviceCollection.AddEntityFrameworkDesignTimeServices(); var serviceProvider = serviceCollection.BuildServiceProvider(); // Add a migration var migrationsScaffolder = serviceProvider.GetRequiredService(); var migration = migrationsScaffolder.ScaffoldMigration(migrationName, rootNamespace); migrationsScaffolder.Save(projectDir, migration, outputDir); ``` -------------------------------- ### Create New Console Project with .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app Use the .NET CLI to create a new console application and navigate into its directory. This is the initial step for setting up your project. ```bash dotnet new console -o EFGetStarted cd EFGetStarted ``` -------------------------------- ### Basic SQL Query with FromSql Source: https://learn.microsoft.com/en-us/ef/core/querying/sql-queries Use `FromSql` to start a LINQ query based on a raw SQL query. This method was introduced in EF Core 7.0. ```csharp var blogs = await context.Blogs .FromSql($ ``` ```csharp SELECT * FROM dbo.Blogs") .ToListAsync(); ``` -------------------------------- ### Install SpatiaLite on Debian/Ubuntu and macOS Source: https://learn.microsoft.com/en-us/ef/core/providers/sqlite/spatial Use APT on Debian/Ubuntu or Homebrew on macOS to install the SpatiaLite library, a dependency for spatial data support. ```bash # Debian/Ubuntu apt-get install libsqlite3-mod-spatialite # macOS brew install libspatialite ``` -------------------------------- ### Compiled Model Bootstrapping Code Example Source: https://learn.microsoft.com/en-us/ef/core/performance/advanced-performance-topics This is an example of the generated bootstrapping code for a compiled model. It includes a static instance and methods for initialization and customization. ```csharp [DbContext(typeof(BlogsContext))] partial class BlogsContextModel : RuntimeModel { private static BlogsContextModel _instance; public static IModel Instance { get { if (_instance == null) { _instance = new BlogsContextModel(); _instance.Initialize(); _instance.Customize(); } return _instance; } } partial void Initialize(); partial void Customize(); } ``` -------------------------------- ### Example: Modifying Entities and Saving Changes Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/events Demonstrates creating a database, adding initial entities, saving them, then retrieving, modifying, deleting, and adding new entities before saving again. This triggers the timestamp events. ```csharp using (var context = new BlogsContext()) { await context.Database.EnsureDeletedAsync(); await context.Database.EnsureCreatedAsync(); context.Add( new Blog { Id = 1, Name = "EF Blog", Posts = { new Post { Id = 1, Title = "EF Core 3.1!" }, new Post { Id = 2, 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 { Id = 3, Title = "EF Core 6.0!" }); await context.SaveChangesAsync(); } ``` -------------------------------- ### Example .config Directory Structure Source: https://learn.microsoft.com/en-us/ef/core/cli/dotnet Place the `dotnet-ef.json` file inside a `.config` directory at the root of your repository. The `dotnet ef` command will search upwards from the current working directory to find the first `.config/dotnet-ef.json` file. ```text / └── .config/ └── dotnet-ef.json ``` -------------------------------- ### Configure GUID as Key Source: https://learn.microsoft.com/en-us/ef/core/providers/cosmos/modeling Use this to configure Entity Framework Core to generate unique, random GUID values at the client for an entity's key property. ```csharp modelBuilder.Entity().Property(b => b.Id).HasValueGenerator(); ``` -------------------------------- ### TrackGraph Output Example Source: https://learn.microsoft.com/en-us/ef/core/change-tracking/explicit-tracking This is an example of the console output generated by the custom TrackGraph logic when processing a graph of entities, showing how each entity is tracked (Modified, Deleted, Added). ```text Tracking Blog with key value 1 as Modified Tracking Post with key value 1 as Modified Tracking Post with key value -2 as Deleted Tracking Post with key value 0 as Added ``` -------------------------------- ### Add Initial Migration for SQL Server and SQLite Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/providers These commands demonstrate how to add an initial migration for both SQL Server and SQLite providers using the .NET CLI. Specify the context type 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 ``` -------------------------------- ### Clone the Repository Source: https://learn.microsoft.com/en-us/ef/core/providers/cosmos/planetary-docs-sample Use this command to clone the sample application's repository to your local machine. ```bash git clone https://github.com/dotnet/EntityFramework.Docs ``` -------------------------------- ### Configure One-to-One Starting from Principal (No Navigation) Source: https://learn.microsoft.com/en-us/ef/core/modeling/relationships/one-to-one Configures a one-to-one relationship starting from the principal entity when there is no navigation property on the principal side. Explicitly specifies the dependent entity type. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasOne() .WithOne(e => e.Blog) .HasForeignKey(e => e.BlogId) .IsRequired(); } ``` -------------------------------- ### Basic DbContext Initialization with OnConfiguring Source: https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration Configure the DbContext by overriding the OnConfiguring method to specify the database provider and connection string. ```csharp public class ApplicationDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer( @"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0"); } } ``` -------------------------------- ### Scaffolding DbContext with .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/templates Use this .NET CLI command to scaffold a DbContext and entities from an existing database. Add --force to overwrite existing files. ```bash dotnet ef dbcontext scaffold "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Chinook" Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Configure Sequential GUID Generation for Non-Key Properties Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server/value-generation Use SequentialGuidValueGenerator to generate sequential GUID values for non-key properties, optimizing performance by avoiding extra database round trips. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().Property(b => b.Guid).HasValueGenerator(typeof(SequentialGuidValueGenerator)); } ``` -------------------------------- ### Add first migration using .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations Use this .NET CLI command to create the initial migration for your EF Core project. ```bash dotnet ef migrations add InitialCreate ``` -------------------------------- ### Apply Migrations using efbundle Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying Execute the generated `efbundle` executable to apply migrations to a local SQL Server instance. Ensure `appsettings.json` is in the same directory. This command is equivalent to `dotnet ef database update`. ```PowerShell .\efbundle.exe --connection 'Data Source=(local)\MSSQLSERVER;Initial Catalog=Blogging;User ID=myUsername;Password={;'$Credential;'here'}' ``` -------------------------------- ### Example EF Core Event Counter Output Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/metrics This is an example of the output you can expect when monitoring EF Core event counters. It displays various metrics such as active DbContexts, query counts, and cache hit rates. ```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 ``` -------------------------------- ### Change Tracker Short View Output Example Source: https://learn.microsoft.com/en-us/ef/core/change-tracking/debug-views This is an example output of the ChangeTracker.DebugView.ShortView after performing add, delete, and modify operations. It shows tracked entities, their states, primary keys, alternate keys, and foreign key values. ```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 ``` -------------------------------- ### Explicit DbContextOptions Creation and Usage Source: https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration Demonstrates how to explicitly create DbContextOptions and then instantiate the DbContext with these options. ```csharp var contextOptions = new DbContextOptionsBuilder() .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0") .Options; using var context = new ApplicationDbContext(contextOptions); ``` -------------------------------- ### Add EF Core Database Provider using .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/providers Install a database provider package using the .NET CLI. Replace 'provider_package_name' with the actual package name. ```bash dotnet add package provider_package_name ``` -------------------------------- ### Create a graph of blogs and posts Source: https://learn.microsoft.com/en-us/ef/core/saving/disconnected-entities Initializes a new blog entity with associated posts. This structure can then be added to the context. ```csharp var blog = new Blog { Url = "http://sample.com", Posts = new List { new Post { Title = "Post 1" }, new Post { Title = "Post 2" }, } }; ``` -------------------------------- ### Install EF Core SQL Server Provider using .NET CLI Source: https://learn.microsoft.com/en-us/ef/core/get-started/overview/install Use the .NET CLI command to add the EF Core SQL Server provider package to your project. You can specify a version using the -v flag. ```bash dotnet add package Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Dynamically Construct Query with Simple Parameterization Source: https://learn.microsoft.com/en-us/ef/core/miscellaneous/context-pooling This example shows how to achieve the same result as the Expression API with parameter, but using a simpler approach without directly invoking the Expression API. It dynamically builds the expression tree more intuitively. ```csharp [Benchmark] public async Task SimpleWithParameter() { var url = "blog" + Interlocked.Increment(ref _blogNumber); using var context = new BloggingContext(); IQueryable query = context.Blogs; if (_addWhereClause) { Expression> whereLambda = b => b.Url == url; query = query.Where(whereLambda); } return await query.CountAsync(); } ``` -------------------------------- ### SQL DELETE Statement Example Source: https://learn.microsoft.com/en-us/ef/core/saving/execute-insert-update-delete This is the SQL statement generated and executed by the ExecuteDeleteAsync() API to delete blogs with a rating below 3. ```sql DELETE FROM [b] FROM [Blogs] AS [b] WHERE [b].[Rating] < 3 ``` -------------------------------- ### Create a Migrations Bundle Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying Use the `dotnet ef migrations bundle` command to create an executable that contains your database migrations. This executable can be deployed and run to apply migrations. ```.NET CLI 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> ``` -------------------------------- ### Employee Entity Definition Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server/temporal-tables Defines a sample `Employee` entity class used in EF Core temporal table examples. ```csharp public class Employee { public Guid EmployeeId { get; set; } public string Name { get; set; } public string Position { get; set; } public string Department { get; set; } public string Address { get; set; } public decimal AnnualSalary { get; set; } } ``` -------------------------------- ### Customer Entity Implementing IHasIntKey Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors An example of a Customer entity that implements the `IHasIntKey` interface, providing an integer Id property. ```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; } } ``` -------------------------------- ### Unmodified SQL for Untagged Queries Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors Example of SQL generated by EF Core for a query that is not tagged and therefore not intercepted for modification. ```sql SELECT [b].[Id], [b].[Name] FROM [Blogs] AS [b] ``` -------------------------------- ### C# SQLite In-Memory Database Setup for Testing Source: https://learn.microsoft.com/en-us/ef/core/testing/testing-without-the-database Sets up an in-memory SQLite database for testing by creating a persistent connection that lasts for the test's duration. This ensures the database is not reset between operations. Includes schema creation and data seeding. ```csharp public SqliteInMemoryBloggingControllerTest() { // Create and open a connection. This creates the SQLite in-memory database, which will persist until the connection is closed // at the end of the test (see Dispose below). _connection = new SqliteConnection("Filename=:memory:"); _connection.Open(); // These options will be used by the context instances in this test suite, including the connection opened above. _contextOptions = new DbContextOptionsBuilder() .UseSqlite(_connection) .Options; // Create the schema and seed some data using var context = new BloggingContext(_contextOptions); if (context.Database.EnsureCreated()) { using var viewCommand = context.Database.GetDbConnection().CreateCommand(); viewCommand.CommandText = @" CREATE VIEW AllResources AS SELECT Url FROM Blogs;"; viewCommand.ExecuteNonQuery(); } context.AddRange( new Blog { Name = "Blog1", Url = "http://blog1.com" }, new Blog { Name = "Blog2", Url = "http://blog2.com" }); context.SaveChanges(); } BloggingContext CreateContext() => new BloggingContext(_contextOptions); public void Dispose() => _connection.Dispose(); ``` -------------------------------- ### Display Historical Data for an Employee Source: https://learn.microsoft.com/en-us/ef/core/providers/sql-server/temporal-tables Retrieve and display the historical records for a specific employee, ordered by their period start 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 ``` -------------------------------- ### Get Daily Message Query Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors This C# code defines a query to retrieve the most recent daily message, tagged for interception. ```csharp async Task GetDailyMessage(DailyMessageContext context) => (await context.DailyMessages.TagWith("Get_Daily_Message").OrderBy(e => e.Id).LastAsync()).Message; ``` -------------------------------- ### Loading multiple navigations with a single Include Source: https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager Load multiple navigations using a single `Include` method when they form reference chains or end with a single collection. This example includes the owner and their authored posts, then drills down to the post's blog owner's photo. ```csharp using (var context = new BloggingContext()) { var blogs = await context.Blogs .Include(blog => blog.Owner.AuthoredPosts) .ThenInclude(post => post.Blog.Owner.Photo) .ToListAsync(); } ``` -------------------------------- ### Apply Migrations from a Bundle Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying Execute the generated bundle (e.g., `efbundle.exe`) to apply the migrations to your database. Migrations are only applied if they haven't been applied already. ```.NET CLI PS C:\local\AllTogetherNow\SixOh> .\efbundle.exe Applying migration '20210903083845_MyMigration'. Done. PS C:\local\AllTogetherNow\SixOh> ``` -------------------------------- ### Dynamic Query Unsuitable for Precompilation Source: https://learn.microsoft.com/en-us/ef/core/performance/nativeaot-and-precompiled-queries This example demonstrates a dynamic query where the `Where` operator is conditionally applied. Such queries cannot be statically analyzed and precompiled. ```csharp IAsyncEnumerable GetBlogs(BlogContext context, bool applyFilter) { IQueryable query = context.Blogs.OrderBy(b => b.Id); if (applyFilter) { query = query.Where(b => b.Name != "foo"); } return query.AsAsyncEnumerable(); } ``` -------------------------------- ### Apply migrations and create database using Package Manager Console Source: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations Execute this PowerShell command in the Package Manager Console to apply all pending migrations and create the database schema. ```powershell Update-Database ``` -------------------------------- ### Modified SQL with Query Hint Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors Example of SQL generated by EF Core when a query is tagged and intercepted to add a query hint. ```sql -- Use hint: robust plan SELECT [b].[Id], [b].[Name] FROM [Blogs] AS [b] OPTION (ROBUST PLAN) ``` -------------------------------- ### Distributor Class Definition Source: https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities Defines a Distributor entity with a collection of StreetAddress shipping centers. This serves as an example for configuring owned types. ```csharp public class Distributor { public int Id { get; set; } public ICollection ShippingCenters { get; set; } } ``` -------------------------------- ### Adding a New Blog Source: https://learn.microsoft.com/en-us/ef/core Creates a new blog instance and adds it to the database. Ensures changes are saved asynchronously. Requires the BloggingContext and necessary using statements. ```C# using (var db = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; db.Blogs.Add(blog); await db.SaveChangesAsync(); } ``` -------------------------------- ### Demonstrate DbSet.Local view with added and deleted entities Source: https://learn.microsoft.com/en-us/ef/core/change-tracking/entity-entries Loads posts, marks one for deletion, adds a new one, and then shows how DbSet.Local reflects these changes. Deleted entities are excluded, and added entities are included in the local view. ```csharp using var context = new BlogsContext(); var posts = await context.Posts.Include(e => e.Blog).ToListAsync(); Console.WriteLine("Local view after loading posts:"); foreach (var post in context.Posts.Local) { Console.WriteLine($" Post: {post.Title}"); } context.Remove(posts[1]); context.Add( new Post { Title = "What’s next for System.Text.Json?", Content = ".NET 5.0 was released recently and has come with many...", Blog = posts[0].Blog }); Console.WriteLine("Local view after adding and deleting posts:"); foreach (var post in context.Posts.Local) { Console.WriteLine($" Post: {post.Title}"); } ``` -------------------------------- ### Sample Application with EF Core and Diagnostic Events Source: https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/diagnostic-listeners A complete console application demonstrating EF Core operations and capturing diagnostic events. It includes setting up the observers and performing database operations. ```csharp 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(); } } ``` -------------------------------- ### Iterate and Modify All Entity Properties Source: https://learn.microsoft.com/en-us/ef/core/change-tracking/entity-entries Use EntityEntry.Properties to loop through all properties of an entity. This example sets any DateTime property to the current time. ```csharp foreach (var propertyEntry in context.Entry(blog).Properties) { if (propertyEntry.Metadata.ClrType == typeof(DateTime)) { propertyEntry.CurrentValue = DateTime.Now; } } ``` -------------------------------- ### ConfigureDbContext and AddDbContext Precedence for Non-Conflicting Options Source: https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration Demonstrates how non-conflicting configurations from `ConfigureDbContext` and `AddDbContext` are composed together. This example adds logging and enables sensitive data logging. ```csharp var services = new ServiceCollection(); services.ConfigureDbContext(options => options.LogTo(Console.WriteLine)); services.AddDbContext(options => options.UseInMemoryDatabase("CompositionExample")); services.ConfigureDbContext(options => options.EnableSensitiveDataLogging()); ```