### Verify EF Core CLI tool installation Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/cli/dotnet.md Run this command to verify that the EF Core CLI tools are correctly installed and to see their version information. ```dotnetcli dotnet ef ``` -------------------------------- ### Install EF Core .NET CLI global tool Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/cli/dotnet.md Use this command to install the Entity Framework Core .NET CLI tools globally on your machine. ```dotnetcli dotnet tool install --global dotnet-ef ``` -------------------------------- ### Install EF Core SQL Server Provider via .NET CLI Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/install.md Installs the Microsoft.EntityFrameworkCore.SqlServer NuGet package using the .NET command-line interface. Supports version specification with the -v modifier for installing specific EF Core versions. ```dotnetcli dotnet add package Microsoft.EntityFrameworkCore.SqlServer ``` ```dotnetcli dotnet add package Microsoft.EntityFrameworkCore.SqlServer -v 6.0.14 ``` -------------------------------- ### Install EF Core SQLite Provider (Visual Studio PMC) Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/first-app.md Installs the Microsoft.EntityFrameworkCore.Sqlite package using the Package Manager Console in Visual Studio. ```powershell Install-Package Microsoft.EntityFrameworkCore.Sqlite ``` -------------------------------- ### SQL Server Sequence Creation Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-7.0/whatsnew.md Example of a SQL Server script to create a sequence for key generation. ```sql CREATE SEQUENCE [ProductSequence] START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE NO CYCLE; ``` -------------------------------- ### Install EF Core Templates Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-7.0/whatsnew.md Install the EF Core templates to customize scaffolded code during reverse engineering. These templates are automatically used by `dotnet ef dbcontext scaffold` and `Scaffold-DbContext`. ```dotnetcli dotnet new install Microsoft.EntityFrameworkCore.Templates dotnet new ef-templates ``` -------------------------------- ### Install EF Core SQL Server Provider via Package Manager Console Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/install.md Installs the Microsoft.EntityFrameworkCore.SqlServer NuGet package using Visual Studio Package Manager Console. Supports version specification with the -Version modifier and package updates via Update-Package command. ```powershell Install-Package Microsoft.EntityFrameworkCore.SqlServer ``` ```powershell Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 6.0.14 ``` ```powershell Update-Package Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Mock Repository for Testing Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/testing/testing-without-the-database.md Example of a mock-based test using Moq to test the controller's interaction with the IBloggingRepository. ```csharp [Fact] public async Task GetBlogReturnsBlogViewModel() { // Arrange var mockRepository = new Mock(); mockRepository .Setup(repo => repo.GetBlogByNameAsync("Test Blog")) .ReturnsAsync(new Blog { Name = "Test Blog" }); var controller = new BloggingControllerWithRepository(mockRepository.Object); // Act var result = await controller.Index("Test Blog"); // Assert var viewResult = Assert.IsType(result); var model = Assert.IsAssignableFrom(viewResult.Model); Assert.Equal("Test Blog", model.Name); } ``` -------------------------------- ### SQL Query Execution Example Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/providers/cosmos/querying.md Illustrates the SQL query that is generated and executed by Entity Framework Core when using the `FromSql` method with a parameter. ```sql SELECT VALUE s FROM ( SELECT VALUE c FROM root c WHERE c.Angle1 <= @p0 ) s ``` -------------------------------- ### LINQ Query Example Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-9.0/whatsnew.md This is a standard LINQ query that will be precompiled for NativeAOT compatibility. ```csharp var blogs = await context.Blogs.Where(b => b.Name == "foo").ToListAsync(); ``` -------------------------------- ### Install EF Core SQL Server Provider NuGet Package Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/providers/sql-server/index.md These commands demonstrate how to install the `Microsoft.EntityFrameworkCore.SqlServer` NuGet package, which is essential for using Entity Framework Core with SQL Server. Options are provided for both the .NET Command Line Interface and the Visual Studio Package Manager Console. ```dotnetcli dotnet add package Microsoft.EntityFrameworkCore.SqlServer ``` ```powershell Install-Package Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Install EF Core SQLite Provider (.NET CLI) Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/first-app.md Adds the Microsoft.EntityFrameworkCore.Sqlite package to your project using the .NET CLI. ```dotnetcli dotnet add package Microsoft.EntityFrameworkCore.Sqlite ``` -------------------------------- ### Filtered Include Example Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/querying/related-data/eager.md Demonstrates how to apply filtering to a collection navigation when using `Include` to load related data. ```csharp var blogs = await context.Blogs .Include(blog => blog.Posts.Where(post => post.Title.Contains("EF"))) .ToListAsync(); ``` -------------------------------- ### Create and track proxy instances with change notifications Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/change-tracking/change-detection.md Demonstrates creating proxy instances using CreateProxy() method instead of standard instantiation. This ensures change notifications are properly tracked. The example queries a blog, modifies its name, and adds a new post using CreateProxy with initialization. ```csharp using var context = new BlogsContext(); var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog"); // Change a property value blog.Name = ".NET Blog (Updated!)"; // Add a new entity to a navigation blog.Posts.Add( context.CreateProxy( p => { p.Title = "What's next for System.Text.Json?"; p.Content = ".NET 5.0 was released recently and has come with many..."; })); Console.WriteLine(context.ChangeTracker.DebugView.LongView); ``` -------------------------------- ### Clone Planetary Docs Repository (Git) Source: https://github.com/dotnet/entityframework.docs/blob/main/samples/end2end/PlanetaryDocs/README.md Use this Git command to clone the Planetary Docs repository from GitHub to your local development environment. This action downloads all project source files, allowing you to get started with the application setup. ```bash git clone https://github.com/dotnet/EntityFramework.Docs ``` -------------------------------- ### Generate Script for Initial Migration Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/cli/dotnet.md Creates a SQL script for the initial database migration, starting from before the first migration (0) up to the 'InitialCreate' migration. ```dotnetcli dotnet ef migrations script 0 InitialCreate ``` -------------------------------- ### Create Database with Migrations (.NET CLI) Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/first-app.md Installs the EF Core tools, scaffolds an initial migration, and applies it to create the database using the .NET CLI. ```dotnetcli dotnet tool install --global dotnet-ef dotnet add package Microsoft.EntityFrameworkCore.Design dotnet ef migrations add InitialCreate dotnet ef database update ``` -------------------------------- ### Enable Lazy Loading with Proxies in DbContextOptions Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/querying/related-data/lazy.md Configure DbContextOptions to use lazy loading proxies. This is a common setup when starting a new DbContext. ```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseLazyLoadingProxies() .UseSqlServer(myConnectionString); ``` -------------------------------- ### Starting to Track a New Entity as Added in C# Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/change-tracking/entity-entries.md This C# example illustrates how to use `context.Entry()` with a new, untracked entity to initiate tracking. It demonstrates that while `Entry()` itself doesn't start tracking a `Detached` entity, subsequently setting its `EntityState` to `Added` will cause the `DbContext` to begin tracking it. ```csharp var newBlog = new Blog(); Debug.Assert(context.Entry(newBlog).State == EntityState.Detached); context.Entry(newBlog).State = EntityState.Added; Debug.Assert(context.Entry(newBlog).State == EntityState.Added); ``` -------------------------------- ### Example EF Core CLI Configuration File Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/cli/dotnet.md This JSON snippet illustrates the structure and all optional properties available for configuring the Entity Framework Core CLI tools. Properties like 'project' and 'startupProject' specify target and startup projects, while 'context' identifies the DbContext class. ```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 } ``` -------------------------------- ### New SQL Parameter Naming Convention Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-10.0/breaking-changes.md Starting with EF Core 10.0, parameter names are simplified to match the originating variable or member name, with a numeric suffix only added when needed. This example shows a parameter named `@city`. ```sql @city='London' SELECT [b].[Id], [b].[Name] FROM [Blogs] AS [b] WHERE [b].[City] = @city ``` -------------------------------- ### Create Database with Migrations (Visual Studio PMC) Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/first-app.md Installs the EF Core tools, scaffolds an initial migration, and applies it to create the database using Visual Studio's Package Manager Console. ```powershell Install-Package Microsoft.EntityFrameworkCore.Tools Add-Migration InitialCreate Update-Database ``` -------------------------------- ### Coloring Open Iconic SVG Sprite Icons with CSS Source: https://github.com/dotnet/entityframework.docs/blob/main/samples/end2end/PlanetaryDocs/PlanetaryDocs/wwwroot/css/open-iconic/README.mdx This CSS example demonstrates how to change the color of an Open Iconic SVG sprite icon. By applying the `fill` property to the specific class of the `` tag, you can easily customize the icon's color. ```css .icon-account-login { fill: #f00; } ``` -------------------------------- ### Demonstrate Entity State Changes and Timestamp Application Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/logging-events-diagnostics/events.md Shows a practical example of creating, modifying, and deleting entities in Entity Framework Core. The code creates a blog with posts, saves changes, then modifies the blog name, removes a post, adds a new post, and saves again to demonstrate how timestamps are applied at each state change. ```csharp using (var context = new BlogsContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); 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!" } } }); context.SaveChanges(); } using (var context = new BlogsContext()) { var blog = context.Blogs.Include(e => e.Posts).Single(); blog.Name = "EF Core Blog"; context.Remove(blog.Posts.First()); blog.Posts.Add(new Post { Id = 3, Title = "EF Core 6.0!" }); context.SaveChanges(); } ``` -------------------------------- ### Main Method with Diagnostic Listener Registration in C# Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/logging-events-diagnostics/diagnostic-listeners.md Demonstrates the complete setup in a console application Main method. Registers the DiagnosticObserver, creates a BlogsContext, performs database operations (delete, create, add data, save changes), and triggers diagnostic events that are captured and logged by the observers. ```csharp public static void Main() { DiagnosticListener.AllListeners.Subscribe(new DiagnosticObserver()); using (var context = new BlogsContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.Add( new Blog { Name = "EF Blog", Posts = { new Post { Title = "EF Core 3.1!" }, new Post { Title = "EF Core 5.0!" } } }); context.SaveChanges(); } } ``` -------------------------------- ### Translate String Manipulations to Azure Cosmos DB Functions Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-6.0/whatsnew.md Demonstrates how EF Core 6.0 translates common .NET string manipulation methods like Length, Trim, ToLower, Substring, and Equals to their corresponding Azure Cosmos DB built-in functions. This example requires a DbContext setup for Azure Cosmos DB. ```csharp var stringResults = context.Triangles.Where( e => e.Name.Length > 4 && e.Name.Trim().ToLower() != "obtuse" && e.Name.TrimStart().Substring(2, 2).Equals("uT", StringComparison.OrdinalIgnoreCase)) .ToList(); ``` ```sql SELECT c FROM root c WHERE ((c["Discriminator"] = "Triangle") AND (((LENGTH(c["Name"]) > 4) AND (LOWER(TRIM(c["Name"])) != "obtuse")) AND STRINGEQUALS(SUBSTRING(LTRIM(c["Name"]), 2, 2), "uT", true))) ``` -------------------------------- ### Execute Migration Bundle with Connection String Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/managing-schemas/migrations/applying.md Apply migrations to a specific database by executing the generated `efbundle.exe` with the `--connection` option, providing the connection string and credentials. ```powershell .\efbundle.exe --connection 'Data Source=(local)\MSSQLSERVER;Initial Catalog=Blogging;User ID=myUsername;Password={;'$Credential;'here'}' ``` -------------------------------- ### Displaying Open Iconic Font Icon with Foundation Classes Source: https://github.com/dotnet/entityframework.docs/blob/main/samples/end2end/PlanetaryDocs/PlanetaryDocs/wwwroot/css/open-iconic/README.mdx This HTML example shows the markup for rendering an Open Iconic font icon when using the Foundation-specific stylesheet. Icons are displayed using `` tags with `fi-icon-name` class, along with `title` and `aria-hidden` attributes for accessibility. ```html ``` -------------------------------- ### Clone the repository Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/providers/cosmos/planetary-docs-sample.md Use this command to clone the Entity Framework documentation repository, which contains the Planetary Docs sample. ```bash git clone https://github.com/dotnet/EntityFramework.Docs ``` -------------------------------- ### Add Default EF Core T4 Templates to Project Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/managing-schemas/scaffolding/templates.md After installing the EF Core template package, this command adds the default T4 templates (`DbContext.t4` and `EntityType.t4`) to your project directory. These files serve as a starting point for customizing the generated DbContext and entity type classes. ```dotnetcli dotnet new ef-templates ``` -------------------------------- ### Multi-Targeted Project Configuration Example Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-10.0/breaking-changes.md This XML snippet shows a project file configuration targeting multiple frameworks. When using EF tools with such projects, the --framework option must be specified. ```xml net8.0;net9.0 ``` -------------------------------- ### Displaying Open Iconic Font Icon with Bootstrap Classes Source: https://github.com/dotnet/entityframework.docs/blob/main/samples/end2end/PlanetaryDocs/PlanetaryDocs/wwwroot/css/open-iconic/README.mdx This HTML example shows the markup for rendering an Open Iconic font icon when using the Bootstrap-specific stylesheet. Icons are displayed using `` tags with `oi` and `oi-icon-name` classes, along with `title` and `aria-hidden` attributes for accessibility. ```html ``` -------------------------------- ### Common Migration Bundle Options Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-6.0/whatsnew.md Explore common options for `dotnet ef migrations bundle`, such as `--output` for specifying the output path, `--context` for selecting a DbContext, and `--verbose` for detailed logging. Use `dotnet ef migrations bundle --help` for a complete list. ```dotnetcli dotnet ef migrations bundle --help ``` -------------------------------- ### Displaying Open Iconic Font Icon with Default Classes Source: https://github.com/dotnet/entityframework.docs/blob/main/samples/end2end/PlanetaryDocs/PlanetaryDocs/wwwroot/css/open-iconic/README.mdx This HTML example shows the markup for rendering an Open Iconic font icon using its default stylesheet. Icons are displayed using `` tags with the `oi` class and a `data-glyph` attribute to specify the icon, along with `title` and `aria-hidden` attributes. ```html ``` -------------------------------- ### Install Older dotnet-ef Tool Version Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-6.0/breaking-changes.md If you need to run the dotnet-ef tool without installing the .NET 6 runtime, install an older version (e.g., 3.1.*). ```dotnetcli dotnet tool install dotnet-ef --version 3.1.* ``` -------------------------------- ### Configure Tenant Provider and DbContextFactory Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/miscellaneous/multitenancy.md Sets up the tenant provider and DbContextFactory in the application startup, using Sqlite as an example. The tenant service is registered with a Scoped lifetime. ```csharp builder.Services.AddDbContextFactory(ServiceLifetime.Scoped); builder.Services.AddScoped(); ``` -------------------------------- ### Apply Migrations from a Bundle Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-7.0/whatsnew.md Migrations bundles can also accept a connection string directly via the `--connection` option, allowing for deployment without a separate configuration file. ```dotnetcli ./bundle.exe --connection "Server=(localdb)\mssqllocaldb;Database=MyAppDb" ``` -------------------------------- ### Get Entities at a Given Level Using GetLevel in LINQ Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/providers/sql-server/hierarchyid.md Retrieves all entities at a specific level in a hierarchical tree using the GetLevel() method in a LINQ Where clause. This example queries a Halflings table to find all family members at a given generation level. The query translates to SQL using the GetLevel() function. ```csharp 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 ``` -------------------------------- ### Apply Migrations with a Bundle Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/managing-schemas/migrations/applying.md Execute the generated bundle (e.g., `efbundle.exe` on Windows) to apply all pending migrations to the database. The bundle checks if migrations have already been applied. ```dotnetcli .\efbundle.exe ``` -------------------------------- ### Migrate SQLite BLOB GUIDs to TEXT format using SQL Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-3.x/breaking-changes.md This SQL script updates existing SQLite databases to convert GUID columns from BLOB to TEXT format. It reconstructs the GUID string from its binary representation, which is necessary after EF Core 3.0 changed its default GUID storage. This script should be run on databases created with older EF Core versions that stored GUIDs as BLOBs. ```sql UPDATE MyTable SET GuidColumn = hex(substr(GuidColumn, 4, 1)) || hex(substr(GuidColumn, 3, 1)) || hex(substr(GuidColumn, 2, 1)) || hex(substr(GuidColumn, 1, 1)) || '-' || hex(substr(GuidColumn, 6, 1)) || hex(substr(GuidColumn, 5, 1)) || '-' || hex(substr(GuidColumn, 8, 1)) || hex(substr(GuidColumn, 7, 1)) || '-' || hex(substr(GuidColumn, 9, 2)) || '-' || hex(substr(GuidColumn, 11, 6)) WHERE typeof(GuidColumn) == 'blob'; ``` -------------------------------- ### Install dotnet ef Global Tool via .NET CLI Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/install.md Installs the dotnet-ef command-line tool globally for executing EF Core commands like migrations and database updates. Can also be installed as a local tool via tool manifest file. ```dotnetcli dotnet tool install --global dotnet-ef ``` ```dotnetcli dotnet tool update --global dotnet-ef ``` -------------------------------- ### Configure Guid to String Conversion in Entity Framework Core Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/modeling/value-conversions.md Shows how to store Guid properties as strings in the standard 'dddddddd-dddd-dddd-dddd-dddddddddddd' format. Enables human-readable GUID storage. ```csharp modelBuilder.Entity() .Property(e => e.YourGuidProperty) .HasConversion(); ``` -------------------------------- ### Add Project Reference to Migrations Project (XML) Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/managing-schemas/migrations/projects.md Add a project reference in your startup project's .csproj file to include the separate migrations project. ```xml ``` -------------------------------- ### Configure GUID Key Generation Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/providers/cosmos/modeling.md Use `GuidValueGenerator` to configure EF Core to generate unique GUID values for the key property at the client. This is useful when you want GUID keys but don't want to manage their generation manually. ```csharp modelBuilder.Entity().Property(b => b.Id).HasValueGenerator(); ``` -------------------------------- ### Configure DbContext Options Composition in C# Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/dbcontext-configuration/index.md This C# example demonstrates how multiple calls to `ConfigureDbContext` and `AddDbContext` compose configuration options. Non-conflicting options, such as logging and enabling sensitive data logging, are combined, while the last specified option for a conflicting setting (like the database provider) takes precedence. It initializes a `ServiceCollection` and configures a `BlogContext` with an in-memory database. ```csharp var services = new ServiceCollection(); services.ConfigureDbContext(options => options.LogTo(Console.WriteLine)); services.AddDbContext(options => options.UseInMemoryDatabase("CompositionExample")); services.ConfigureDbContext(options => options.EnableSensitiveDataLogging()); var serviceProvider = services.BuildServiceProvider(); ``` -------------------------------- ### Install EF Core Design Package via .NET CLI Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/install.md Installs the Microsoft.EntityFrameworkCore.Design NuGet package required for EF Core tooling functionality. Must match the major version of runtime packages. ```dotnetcli dotnet add package Microsoft.EntityFrameworkCore.Design ``` -------------------------------- ### Initialize DbContext with constructor-injected connection string in C# Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/dbcontext-configuration/index.md This C# example shows how to pass a connection string to the `DbContext` constructor, allowing for dynamic configuration. The `OnConfiguring` method then uses this injected string to set up the SQL Server provider. This pattern enhances flexibility by decoupling the connection string from the class definition. ```csharp public class ApplicationDbContext : DbContext { private readonly string _connectionString; public ApplicationDbContext(string connectionString) { _connectionString = connectionString; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(_connectionString); } } ``` -------------------------------- ### Configure Guid to Byte Array Conversion in Entity Framework Core Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/modeling/value-conversions.md Demonstrates storing Guid properties as byte arrays in .NET binary serialization order. Provides compact binary storage format for GUIDs. ```csharp modelBuilder.Entity() .Property(e => e.YourGuidProperty) .HasConversion(); ``` -------------------------------- ### Install SpatiaLite on Debian/Ubuntu and macOS Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/providers/sqlite/spatial.md Use package managers to install the native 'mod_spatialite' library on different operating systems. ```bash # Debian/Ubuntu apt-get install libsqlite3-mod-spatialite # macOS brew install libspatialite ``` -------------------------------- ### Create New Console Project (.NET CLI) Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/first-app.md Creates a new console application and navigates into its directory using the .NET CLI. ```dotnetcli dotnet new console -o EFGetStarted cd EFGetStarted ``` -------------------------------- ### Install EF Core Tools Package via Package Manager Console Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/get-started/overview/install.md Installs the Microsoft.EntityFrameworkCore.Tools NuGet package in Visual Studio to enable Package Manager Console commands for EF Core operations like Add-Migration and Update-Database. ```powershell Install-Package Microsoft.EntityFrameworkCore.Tools ``` -------------------------------- ### Optimize DbContext using default settings (PowerShell) Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/cli/powershell.md This example demonstrates how to optimize a DbContext model using the `Optimize-DbContext` cmdlet without any parameters. It assumes there is only one DbContext in the project and uses default output directory and namespace settings for the generated compiled model. ```powershell Optimize-DbContext ``` -------------------------------- ### Configure Sequential GUID for Non-Key Properties Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/providers/sql-server/value-generation.md Configure EF to generate sequential GUID values for non-key properties using SequentialGuidValueGenerator. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().Property(b => b.Guid).HasValueGenerator(typeof(SequentialGuidValueGenerator)); } ``` -------------------------------- ### Dynamic Query Example Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/performance/nativeaot-and-precompiled-queries.md This example demonstrates a dynamic query where the 'Where' operator is conditionally applied. Such queries cannot be precompiled because they cannot be statically analyzed. ```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(); } ``` -------------------------------- ### Implement BloggingRepository with EF Core Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/testing/testing-without-the-database.md A sample implementation of the IBloggingRepository interface using EF Core's BloggingContext. Note the return type IAsyncEnumerable to facilitate stubbing. ```csharp 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... } ``` -------------------------------- ### Get `EntityEntry` for Untracked Instance Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-7.0/whatsnew.md Use the `Entry` method on `DbSet` to get the `EntityEntry` for an instance, even if it's not yet tracked by the context. ```csharp var state = context.BuildMetadata.Entry(build).State; ``` -------------------------------- ### Example Query for Indexing Analysis - C# Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/performance/efficient-querying.md This C# code snippet demonstrates a typical query that can be analyzed for index utilization. Examine its query plan to identify potential performance issues related to indexing. ```csharp using var context = new BloggingContext(); var posts = context.Posts.Where(p => p.Url.StartsWith("http://")).OrderBy(p => p.Content).ToList(); ``` -------------------------------- ### Apply Migrations with Connection String Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-7.0/whatsnew.md When applying migrations, you can specify the connection string directly using the `--connection` option. This is an alternative to relying on configuration files. ```text dotnet ef database update --connection "Server=(localdb)\mssqllocaldb;Database=MyAppDb" ``` -------------------------------- ### Configure EF Core GUID property to use BLOB storage with a Value Converter (C#) Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-3.x/breaking-changes.md This C# code snippet demonstrates how to configure an EF Core `Guid` property to continue storing GUIDs as BLOBs, overriding the new default TEXT storage in EF Core 3.0. It uses a value converter to translate between `Guid` objects and byte arrays for database interaction. This is a mitigation for applications that rely on the old BLOB storage behavior. ```csharp modelBuilder .Entity() .Property(e => e.GuidProperty) .HasConversion( g => g.ToByteArray(), b => new Guid(b)); ``` -------------------------------- ### Configure SQL Server Provider in DbContext Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/providers/index.md Example of configuring the SQL Server provider within the `OnConfiguring` method of your `DbContext`. This sets up the connection string for the database. ```csharp optionsBuilder.UseSqlServer( @"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;"); ``` -------------------------------- ### Eager Loading and Projection for Efficiency Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/performance/efficient-querying.md Shows how to efficiently load related entities and project only necessary properties using EF Core. This example fetches blogs and their posts in a single query, avoiding the N+1 problem. ```csharp var blogsAndPosts = context.Blogs .Include(b => b.Posts) .Select(b => new { Blog = b, Posts = b.Posts.ToList() }) .ToList(); foreach (var item in blogsAndPosts) { Console.WriteLine($"Blog: {item.Blog.Url}"); foreach (var post in item.Posts) { Console.WriteLine($" Post: {post.Title}"); } } ``` -------------------------------- ### Split Query Example 2: Single vs. Multiple SQL Queries for Dates Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-6.0/whatsnew.md Compares the SQL output for projecting order dates from a collection. The first query demonstrates a single SQL translation, while the second shows the multiple query approach. ```sql SELECT [c].[Id], [t].[OrderDate], [t].[Id] FROM [Customers] AS [c] LEFT JOIN ( SELECT [o].[OrderDate], [o].[Id], [o].[CustomerId] FROM [Order] AS [o] WHERE [o].[Id] > 1 ) AS [t] ON [c].[Id] = [t].[CustomerId] ORDER BY [c].[Id] ``` ```sql SELECT [c].[Id] FROM [Customers] AS [c] ORDER BY [c].[Id] SELECT [t].[Id], [t].[CustomerId], [t].[OrderDate], [c].[Id] FROM [Customers] AS [c] INNER JOIN ( SELECT [o].[Id], [o].[CustomerId], [o].[OrderDate] FROM [Order] AS [o] WHERE [o].[Id] > 1 ) AS [t] ON [c].[Id] = [t].[CustomerId] ORDER BY [c].[Id] ``` -------------------------------- ### EF Core Connection Usage Example Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-6.0/whatsnew.md This code demonstrates the typical usage pattern of opening and closing database connections for each operation in EF Core. Observe the connection lifecycle logging. ```csharp [!code-csharp[ConnectionExample](../../../../samples/core/Miscellaneous/NewInEFCore6/SqliteSamples.cs?name=ConnectionExample)] ``` -------------------------------- ### Example dotnet-counters Output Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/logging-events-diagnostics/metrics.md This is an example of the output you can expect when monitoring EF Core event counters. It shows various metrics like Active DbContexts, Queries, and SaveChanges. ```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 ``` -------------------------------- ### DocFX Build and Serve Command - Windows Source: https://github.com/dotnet/entityframework.docs/blob/main/CONTRIBUTING.md Console command to build and locally host the documentation site using DocFX on Windows. Requires DocFX to be added to PATH and executed from the repository root containing docfx.json. ```console docfx -t default --serve ``` -------------------------------- ### Define Field-Only Property Matching Field Name (EF Core >= 3.0) Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-3.x/breaking-changes.md This C# snippet demonstrates the new behavior in EF Core 3.0 and later for field-only properties. Starting with EF Core 3.0, a field-only property must exactly match the name of its backing field. This change aims to prevent ambiguity and align mapping rules more closely with CLR properties. The example shows how to configure a property named `_id` to map directly to a backing field also named `_id`. ```csharp modelBuilder .Entity() .Property("_id"); ``` -------------------------------- ### Insert Book Entity with Primitive Collections Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/providers/cosmos/modeling.md Demonstrates how to create a new 'Book' entity, populate its primitive collections (Quotes and Notes), and persist it to the database using EF Core's DbContext. This example shows the initial population of these collections. ```csharp using var context = new BooksContext(); var book = new Book { Title = "How It Works: Incredible History", Quotes = new List { "Thomas (Tommy) Flowers was the British engineer behind the design of the Colossus computer.", "Invented originally for Guinness, plastic widgets are nitrogen-filled spheres.", "For 20 years after its introduction in 1979, the Walkman dominated the personal stereo market." }, Notes = new Dictionary { { "121", "Fridges" }, { "144", "Peter Higgs" }, { "48", "Saint Mark\'s Basilica" }, { "36", "The Terracotta Army" } } }; context.Add(book); context.SaveChanges(); ``` -------------------------------- ### SQL Server Table Creation for Configured Properties Source: https://github.com/dotnet/entityframework.docs/blob/main/entity-framework/core/what-is-new/ef-core-6.0/whatsnew.md Illustrates the SQL Server table schema generated by migrations, showing how the Money type is mapped to nvarchar(64). ```sql CREATE TABLE [Customers] ( [Id] int NOT NULL IDENTITY, [Name] varchar(1024) NULL, [IsActive] int NOT NULL, [AccountValue] nvarchar(64) NOT NULL, CONSTRAINT [PK_Customers] PRIMARY KEY ([Id]) ); CREATE TABLE [Order] ( [Id] int NOT NULL IDENTITY, [SpecialInstructions] varchar(1024) NULL, [OrderDate] bigint NOT NULL, [IsComplete] int NOT NULL, [Price] nvarchar(64) NOT NULL, [Discount] nvarchar(64) NULL, [CustomerId] int NULL, CONSTRAINT [PK_Order] PRIMARY KEY ([Id]), CONSTRAINT [FK_Order_Customers_CustomerId] FOREIGN KEY ([CustomerId]) REFERENCES [Customers] ([Id]) ); ```