### Install EF Core Templates Package
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Templates/README.md
Install the Microsoft.EntityFrameworkCore.Templates NuGet package using the dotnet CLI.
```bash
dotnet new install Microsoft.EntityFrameworkCore.Templates
```
--------------------------------
### Installation
Source: https://github.com/dotnet/efcore/blob/main/src/Microsoft.Data.Sqlite/README.md
Instructions on how to install the Microsoft.Data.Sqlite package using the .NET CLI.
```APIDOC
## Installation
### Description
Installs the latest stable version of the Microsoft.Data.Sqlite package.
### Method
.NET CLI Command
### Endpoint
N/A
### Parameters
#### Query Parameters
- **--version** (string) - Optional - Specify a preview version to install.
### Request Example
```sh
dotnet add package Microsoft.Data.Sqlite
```
### Response
#### Success Response (0)
Package installed successfully.
#### Response Example
```
Successfully installed Microsoft.Data.Sqlite.
```
```
--------------------------------
### Install Daily Build EF Command-Line Tool
Source: https://github.com/dotnet/efcore/blob/main/docs/DailyBuilds.md
Installs the daily build version of the EF command-line tool globally. This command requires the custom NuGet package source to be configured. Use this when you need the latest features or bug fixes in the CLI.
```sh
dotnet tool install -g dotnet-ef --version 11.0.0-* --add-source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet11/nuget/v3/index.json
```
--------------------------------
### Example of Using 1ES Official Templates with Multiple Outputs
Source: https://github.com/dotnet/efcore/blob/main/eng/common/template-guidance.md
This example demonstrates how to configure a pipeline to use 1ES official templates, specifically leveraging the 'multiple outputs' feature to consolidate artifact publishing and reduce security scans. Ensure publish artifacts are located in the `$(Build.ArtifactStagingDirectory)`.
```yaml
extends:
template: azure-pipelines/MicroBuild.1ES.Official.yml@MicroBuildTemplate
parameters:
stages:
- stage: build
jobs:
- template: /eng/common/templates-official/jobs/jobs.yml@self
parameters:
# 1ES makes use of outputs to reduce security task injection overhead
templateContext:
outputs:
- output: pipelineArtifact
displayName: 'Publish logs from source'
continueOnError: true
condition: always()
targetPath: $(Build.ArtifactStagingDirectory)/artifacts/log
artifactName: Logs
jobs:
- job: Windows
steps:
- script: echo "friendly neighborhood" > artifacts/marvel/spiderman.txt
# copy build outputs to artifact staging directory for publishing
- task: CopyFiles@2
displayName: Gather build output
inputs:
SourceFolder: '$(System.DefaultWorkingDirectory)/artifacts/marvel'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/marvel'
```
--------------------------------
### Install `dotnet-ef` Tool
Source: https://github.com/dotnet/efcore/blob/main/src/dotnet-ef/README.md
Installs the cross-platform Entity Framework Core command-line tool globally. This tool is essential for managing EF Core migrations and performing other design-time tasks.
```dotnetcli
dotnet tool install --global dotnet-ef
```
--------------------------------
### Basic Usage
Source: https://github.com/dotnet/efcore/blob/main/src/Microsoft.Data.Sqlite/README.md
Example of how to use Microsoft.Data.Sqlite to connect to a SQLite database, execute a query, and read the results.
```APIDOC
## Basic Usage
### Description
Demonstrates basic ADO.NET operations using Microsoft.Data.Sqlite to query a SQLite database.
### Method
C# Code Snippet
### Endpoint
N/A
### Parameters
N/A
### Request Example
```cs
using var connection = new SqliteConnection("Data Source=Blogs.db");
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = "SELECT Url FROM Blogs";
using var reader = command.ExecuteReader();
while (reader.Read())
{
var url = reader.GetString(0);
}
```
### Response
#### Success Response (200)
Data read from the database.
#### Response Example
```
// Example data read from the database
var url = "http://example.com/blog";
```
```
--------------------------------
### Install EF Core Packages (C#)
Source: https://github.com/dotnet/efcore/blob/main/README.md
Installs the necessary Entity Framework Core provider packages for SQL Server, SQLite, and Cosmos DB using the .NET CLI. This enables EF Core to interact with these specific database systems. The `--version` option can be used to specify a preview version.
```sh
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Cosmos
```
--------------------------------
### Basic EF Core Usage (C#)
Source: https://github.com/dotnet/efcore/blob/main/README.md
Demonstrates fundamental Entity Framework Core operations including adding, querying, updating, and deleting data. This example assumes a `BloggingContext` and `Blog`/`Post` entities are defined. It utilizes LINQ for querying and change tracking for persistence.
```cs
using var db = new BloggingContext();
// Inserting data into the database
db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
db.SaveChanges();
// Querying
var blog = db.Blogs
.OrderBy(b => b.BlogId)
.First();
// Updating
blog.Url = "https://devblogs.microsoft.com/dotnet";
blog.Posts.Add(
new Post
{
Title = "Hello World",
Content = "I wrote an app using EF Core!"
});
db.SaveChanges();
// Deleting
db.Remove(blog);
db.SaveChanges();
```
--------------------------------
### Install Daily Build EF Reverse Engineering Templates
Source: https://github.com/dotnet/efcore/blob/main/docs/DailyBuilds.md
Installs the daily build version of EF reverse engineering (scaffolding) templates. This is useful for experimenting with new features or testing bug fixes in the scaffolding process. It also requires the custom NuGet package source.
```sh
dotnet new install Microsoft.EntityFrameworkCore.Templates::11.0.0-* --add-source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet11/nuget/v3/index.json
```
--------------------------------
### EF Core CLI Help Command
Source: https://github.com/dotnet/efcore/blob/main/src/dotnet-ef/README.md
Displays general help information and lists available commands for the Entity Framework Core command-line interface. This is a useful starting point for understanding the tool's capabilities.
```dotnetcli
dotnet ef --help
```
--------------------------------
### Install Microsoft.Data.Sqlite Package (C#)
Source: https://github.com/dotnet/efcore/blob/main/README.md
Installs the Microsoft.Data.Sqlite ADO.NET provider package using the .NET CLI. This package allows applications to interact with SQLite databases directly or as a foundation for the EF Core SQLite provider. The `--version` option can be used to specify a preview version.
```sh
dotnet add package Microsoft.Data.Sqlite
```
--------------------------------
### Enable Both Lazy-Loading and Change-Tracking Proxies in EF Core
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Proxies/README.md
This example illustrates how to configure a DbContext to utilize proxies that support both lazy-loading and change-tracking simultaneously. Both UseLazyLoadingProxies() and UseChangeTrackingProxies() are chained in the OnConfiguring method.
```csharp
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies()
.UseChangeTrackingProxies();
```
--------------------------------
### Configure SQLite Provider in EF Core
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Sqlite/README.md
This snippet demonstrates how to override the OnConfiguring method in a DbContext class to specify the SQLite connection string. It requires the Microsoft.EntityFrameworkCore.Sqlite package to be installed in the project.
```csharp
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=database.db");
}
```
--------------------------------
### Initialize SQLitePCLRaw Batteries
Source: https://github.com/dotnet/efcore/blob/main/src/Microsoft.Data.Sqlite.Core/Package.md
This code snippet demonstrates how to initialize the SQLite native binary provider. It is required when using the Core package to ensure the underlying SQLite library is loaded correctly.
```csharp
SQLitePCL.Batteries_V2.Init();
```
--------------------------------
### Basic SQLite Connection and Query in C#
Source: https://github.com/dotnet/efcore/blob/main/README.md
Demonstrates how to establish a connection to an SQLite database, create a command, execute a query, and read the results using ADO.NET abstractions in C#. This snippet utilizes the SqliteConnection, SqliteCommand, and SqliteDataReader classes.
```csharp
using var connection = new SqliteConnection("Data Source=Blogs.db");
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = "SELECT Url FROM Blogs";
using var reader = command.ExecuteReader();
while (reader.Read())
{
var url = reader.GetString(0);
}
```
--------------------------------
### Specify EF Core Startup Project (MSBuild)
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Tasks/README.md
When the Entity Framework Core startup project differs from the current project, it must be explicitly specified using the `$(EFStartupProject)` MSBuild property. This ensures that the EF Core design-time tools can correctly locate and reference the startup project's dependencies.
```xml
..\Startup\Startup.csproj
```
--------------------------------
### Create Customer with Parameterized Input (C#)
Source: https://github.com/dotnet/efcore/wiki/Security
This C# method demonstrates creating a new customer in the database using parameterized input for first and last names. This prevents SQL injection by treating user-supplied data as values rather than executable SQL.
```csharp
public Customer CreateCustomer(string firstName, string lastName)
{
using(var context = new CustomerContext())
{
var customer = new Customer
{
FirstName = firstName,
LastName = lastName
};
context.Customers.Add(customer);
context.SaveChanges();
return customer;
}
}
```
```sql
INSERT INTO [Customer] ([FirstName], [LastName])
OUTPUT INSERTED.[CustomerId]
VALUES (@p0, @p1)
```
--------------------------------
### Configure SQL Server Provider in EF Core
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore/README.md
Illustrates how to override the OnConfiguring method in a DbContext to specify a connection string and use the SQL Server database provider.
```csharp
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyDatabase");
public DbSet Customers { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
```
--------------------------------
### Build EF Core Project
Source: https://github.com/dotnet/efcore/blob/main/docs/getting-and-building-the-code.md
Commands to execute the build script and generate local NuGet packages with custom build numbers.
```console
build
```
```console
build /p:OfficialBuildId=20231212.6 -pack
```
--------------------------------
### Open EFCore Solution in Visual Studio
Source: https://github.com/dotnet/efcore/blob/main/docs/getting-and-building-the-code.md
Opens the EFCore solution file in Visual Studio, ensuring the correct .NET Core SDK and environment variables are set. This script is a wrapper and may open any default application for .sln files.
```console
startvs.cmd EFCore.sln
```
--------------------------------
### Configure SQLite with NetTopologySuite in EF Core
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Sqlite.NTS/README.md
Demonstrates how to configure the SQLite database provider for DbContext to include NetTopologySuite support. This is done by calling `UseNetTopologySuite` within the `UseSqlite` configuration.
```csharp
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> options.UseSqlite("Data Source=spatialdata.dat", b => b.UseNetTopologySuite());
```
--------------------------------
### Configure EF Core to use SQL Server
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.SqlServer/README.md
This snippet shows how to configure your DbContext to use the SQL Server database provider by calling the `UseSqlServer` method.
```APIDOC
## Configure EF Core to use SQL Server
### Description
This example demonstrates how to configure your `DbContext` to utilize the SQL Server database provider by invoking the `UseSqlServer` method within the `OnConfiguring` override.
### Method
`OnConfiguring` override within `DbContext`
### Endpoint
N/A (Configuration within application code)
### Parameters
N/A
### Request Body
N/A
### Request Example
```csharp
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
}
```
### Response
N/A (Configuration, not an API call)
### Response Example
N/A
```
--------------------------------
### Emit API summary
Source: https://github.com/dotnet/efcore/blob/main/eng/Tools/ApiChief/README.md
Produces a human-readable summary of the public API surface.
```console
dotnet ApiChief.dll MyAssembly.dll emit summary
```
--------------------------------
### Generate EF Core Templates
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Templates/README.md
Generate T4 templates for scaffolding within your project using the dotnet CLI.
```bash
dotnet new ef-templates
```
--------------------------------
### Configure DbContext with Cosmos Provider
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Cosmos/README.md
Demonstrates how to use the `UseCosmos` method within `OnConfiguring` to specify Azure Cosmos DB as the database provider for your DbContext. This involves providing the connection endpoint, account key, and database name.
```csharp
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseCosmos(
"https://localhost:8081",
"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
databaseName: "OrdersDB");
```
--------------------------------
### Configure NuGet Package Source
Source: https://github.com/dotnet/efcore/blob/main/docs/DailyBuilds.md
This XML configuration file sets up custom NuGet package sources required to access daily builds of .NET EF Core. It includes the 'dotnet11' source for daily builds and 'nuget.org' for standard packages. Place this file next to your solution or csproj file.
```xml
```
--------------------------------
### Run EFCore Tests from Command Line
Source: https://github.com/dotnet/efcore/blob/main/docs/getting-and-building-the-code.md
Executes all tests for the EFCore project using the command line. This command should be run after the project has been successfully built.
```console
test
```
--------------------------------
### Configure NuGet Local Source
Source: https://github.com/dotnet/efcore/blob/main/docs/getting-and-building-the-code.md
An XML configuration snippet to add a local directory as a NuGet package source for testing custom builds.
```xml
```
--------------------------------
### Clone EF Core Repository
Source: https://github.com/dotnet/efcore/blob/main/docs/getting-and-building-the-code.md
Commands to clone the official EF Core repository or a personal fork using Git.
```console
git clone https://github.com/dotnet/efcore.git
```
```console
git clone https://github.com/myusername/efcore.git
```
--------------------------------
### Define DbContext and Entities in EF Core
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore/README.md
Demonstrates how to create a custom DbContext class that inherits from Microsoft.EntityFrameworkCore.DbContext and define entity classes to represent database tables.
```csharp
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public DbSet Customers { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
```
--------------------------------
### Configure DbContext with Azure Cosmos DB
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Cosmos/README.md
Demonstrates how to configure your DbContext to use the Azure Cosmos DB provider by calling the `UseCosmos` method.
```APIDOC
## Configure DbContext with Azure Cosmos DB
### Description
This snippet shows how to configure your `DbContext` to use the Azure Cosmos DB provider. You achieve this by calling the `UseCosmos` method within your `OnConfiguring` method.
### Method
C# (within DbContext)
### Endpoint
N/A (Configuration within application code)
### Parameters
N/A
### Request Example
```csharp
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseCosmos(
"https://localhost:8081",
"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
databaseName: "OrdersDB");
```
### Response
N/A (Configuration step)
### Response Example
N/A
```
--------------------------------
### Perform CRUD Operations with EF Core
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore/README.md
Shows how to instantiate a DbContext to add new records to the database and retrieve existing data using LINQ queries.
```csharp
using var context = new MyDbContext();
// Add a new customer
context.Customers.Add(new Customer { Name = "John Doe" });
context.SaveChanges();
// Retrieve all customers
var customers = context.Customers.ToList();
```
--------------------------------
### Emit API baseline
Source: https://github.com/dotnet/efcore/blob/main/eng/Tools/ApiChief/README.md
Generates a JSON file representing the public API surface of an assembly.
```console
dotnet ApiChief.dll MyAssembly.dll emit baseline -o MyAssembly.baseline.json
```
--------------------------------
### Configure EF Core Design Package Reference
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Design/README.md
This XML snippet demonstrates how to add the Microsoft.EntityFrameworkCore.Design package to a .NET project file. It includes the PrivateAssets configuration to ensure the tooling is not bundled with the final published application.
```xml
all
runtime; build; native; contentfiles; analyzers; buildtransitive
```
--------------------------------
### EF Core DbContext Management Commands
Source: https://github.com/dotnet/efcore/blob/main/src/dotnet-ef/README.md
Offers commands for interacting with your `DbContext` in Entity Framework Core. These commands allow you to retrieve information about your context, list available contexts, optimize the model, scaffold from an existing database, and generate SQL scripts.
```dotnetcli
dotnet ef dbcontext info
dotnet ef dbcontext list
dotnet ef dbcontext optimize
dotnet ef dbcontext scaffold
dotnet ef dbcontext script
```
--------------------------------
### Emit API review files
Source: https://github.com/dotnet/efcore/blob/main/eng/Tools/ApiChief/README.md
Generates source files intended for API review processes.
```console
dotnet ApiChief.dll MyAssembly.dll emit review
```
--------------------------------
### Configure In-Memory Database in DbContext
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.InMemory/README.md
This snippet demonstrates how to override the OnConfiguring method in a DbContext class to specify the use of the in-memory database provider. It requires the Microsoft.EntityFrameworkCore.InMemory NuGet package.
```csharp
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("MyDatabase");
}
```
--------------------------------
### EF Core Database Management Commands
Source: https://github.com/dotnet/efcore/blob/main/src/dotnet-ef/README.md
Provides commands for managing the database schema with Entity Framework Core. This includes dropping the entire database, updating it to the latest or a specific migration, and generating SQL scripts.
```dotnetcli
dotnet ef database drop
dotnet ef database update
dotnet ef database script
```
--------------------------------
### Update Owner with Raw SQL and Parameters (C#)
Source: https://github.com/dotnet/efcore/wiki/Security
This C# method shows how to update a customer's owner using a raw SQL command with parameters. It accesses the underlying ADO.NET DbCommand to execute the SQL, ensuring that the owner names are passed as parameters to prevent SQL injection.
```csharp
public void MoveClients(string oldOwner, string newOwner)
{
using (var context = new OrdersContext(str))
{
var connection = context.Database.AsRelational().Connection.DbConnection;
var cmd = connection .CreateCommand();
cmd.CommandText = "UPDATE [dbo].[Customer] SET [Owner] = @p0 WHERE [Owner] = @p1";
cmd.Parameters.Add(new SqlParameter("p0", "newOwner"));
cmd.Parameters.Add(new SqlParameter("p1", "oldOwner"));
connection .Open();
cmd.ExecuteNonQuery();
connection .Close();
}
}
```
--------------------------------
### Use Wildcards for Daily Build Package Versions
Source: https://github.com/dotnet/efcore/blob/main/docs/DailyBuilds.md
Configures project references to use the latest daily build versions of EF Core packages by employing wildcards in the version string. This ensures that NuGet restores the most recent daily build available whenever packages are restored. This is the easiest way to consume daily builds.
```xml
```
--------------------------------
### Configure Clean NuGet Package Sources
Source: https://github.com/dotnet/efcore/blob/main/docs/DailyBuilds.md
This configuration provides a clean slate for NuGet package management by clearing both disabled sources and existing package sources. It is recommended for environments where you want to explicitly define all package feeds to avoid conflicts.
```xml
```
--------------------------------
### Configure NuGet Package Sources with Enabled Sources
Source: https://github.com/dotnet/efcore/blob/main/docs/DailyBuilds.md
This XML configuration clears any disabled package sources and adds the necessary EF Core daily build feed alongside the standard NuGet.org source. It ensures that previously disabled sources do not interfere with package restoration.
```xml
```
--------------------------------
### Configure SQL Server with NetTopologySuite in EF Core
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.SqlServer.NTS/README.md
This code snippet demonstrates how to configure the SQL Server database provider for Entity Framework Core to use NetTopologySuite for spatial data. It involves calling the `UseNetTopologySuite` extension method within the `UseSqlServer` configuration.
```csharp
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> options.UseSqlServer(
"Server=localhost;Database=MyDatabase;Trusted_Connection=True;",
b => b.UseNetTopologySuite());
```
--------------------------------
### Configure Migrations Assembly in EF Core
Source: https://github.com/dotnet/efcore/blob/main/docs/threat_model.md
Demonstrates how to explicitly specify the assembly containing migration files within the DbContext configuration. This is necessary for runtime migration operations when the migrations are not in the main application assembly.
```csharp
services.AddDbContext(options => options.UseSqlServer(
x => x.MigrationsAssembly("WebApplication1.Migrations")));
```
--------------------------------
### Enable Lazy-Loading Proxies in EF Core DbContext Configuration
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Proxies/README.md
This code snippet demonstrates how to enable lazy-loading proxies for a DbContext using the UseLazyLoadingProxies() extension method. This is typically done within the OnConfiguring method of your DbContext class.
```csharp
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseLazyLoadingProxies();
```
--------------------------------
### Configure EF Core Code Generation Stage (MSBuild)
Source: https://github.com/dotnet/efcore/blob/main/src/EFCore.Tasks/README.md
Control the stage at which Entity Framework Core code generation occurs during the build process. This is achieved by setting MSBuild properties. The `$(EFScaffoldModelStage)` and `$(EFPrecompileQueriesStage)` properties can be set to 'publish' or 'build' to define the generation stage. Any other value disables the respective generation.
```xml
publish
build
```
--------------------------------
### EF Core Migrations Management Commands
Source: https://github.com/dotnet/efcore/blob/main/src/dotnet-ef/README.md
Encompasses commands for managing migrations in Entity Framework Core projects. You can add new migrations, bundle them for deployment, check for pending model changes, list existing migrations, remove the last migration, and generate SQL scripts from migrations.
```dotnetcli
dotnet ef migrations add
dotnet ef migrations bundle
dotnet ef migrations has-pending-model-changes
dotnet ef migrations list
dotnet ef migrations remove
dotnet ef migrations script
```