### Example: Using Storage Parameters for Table Optimization Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Illustrates how to retrieve and use PostgreSQL storage parameters for table optimization. The example value shows a typical format for these parameters. ```csharp // Storage parameters control table optimization var storageParams = entityType.GetStorageParameters(); // Example value: "fillfactor=70, autovacuum_vacuum_scale_factor=0.01" ``` -------------------------------- ### Dependency Injection Setup in C# Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/README.md Configure Npgsql DbContext for dependency injection using AddNpgsql or manually registering the provider and DbContext. ```csharp services.AddNpgsql( "Host=localhost;Database=blogs", npgsqlOptions => npgsqlOptions.SetPostgresVersion(15, 0)); // Or manually register the provider services.AddEntityFrameworkNpgsql(); services.AddDbContext(options => options.UseNpgsql(connectionString)); ``` -------------------------------- ### Example Usage of NpgsqlRetryingExecutionStrategy Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Demonstrates how to instantiate NpgsqlRetryingExecutionStrategy with custom retry settings, including a specific error code for serialization failures. ```csharp var strategy = new NpgsqlRetryingExecutionStrategy( context, maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: new[] { "40P01" } // Serialization failure ); ``` -------------------------------- ### Example: Configuring Identity Column with Options Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/model-builder-extensions.md Demonstrates chaining UseIdentityByDefaultColumn with HasIdentityOptions to configure a property's identity column behavior, including min/max values and cycle settings. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .Property(b => b.Id) .UseIdentityByDefaultColumn(seed: 1, increment: 1) .HasIdentityOptions(minValue: 1, maxValue: long.MaxValue, cycle: false); } ``` -------------------------------- ### Get PostgreSQL Version Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the target PostgreSQL version for the model. Returns the configured version, or null for default. ```csharp public static Version? GetPostgresVersion(this IReadOnlyModel model) ``` -------------------------------- ### Get Direct Sequence Schema Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the schema of the direct sequence. ```csharp public static string? GetSequenceSchema(this IReadOnlyProperty property) ``` -------------------------------- ### Get Direct Sequence Name Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the name of the direct sequence (non-hi-lo). ```csharp public static string? GetSequenceName(this IReadOnlyProperty property) ``` -------------------------------- ### Create PostgreSQL Table Partition via Migration Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/migrations-and-extensions.md Configure PostgreSQL table partitioning by executing raw SQL commands within your EF Core migrations. This example creates a monthly partition for an 'Orders' table. ```csharp protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Orders", columns: table => new { Id = table.Column(), CreatedDate = table.Column(), Amount = table.Column() }); // Create partition migrationBuilder.Sql(@" CREATE TABLE Orders_2024 PARTITION OF Orders FOR VALUES FROM ('2024-01-01') TO ('2025-01-01'); "); } ``` -------------------------------- ### Get Sequence Name Suffix Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the suffix appended to generated sequence names. ```csharp public static string? GetSequenceNameSuffix(this IReadOnlyModel model) ``` -------------------------------- ### Get Identity Options Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the PostgreSQL IDENTITY column options for this property. Returns null if not configured. ```csharp public static IdentitySequenceOptionsData? GetIdentityOptions( this IReadOnlyProperty property) ``` ```csharp var options = property.GetIdentityOptions(); if (options != null) { Console.WriteLine($"Start Value: {options.StartValue}"); Console.WriteLine($"Increment: {options.IncrementBy}"); Console.WriteLine($"Min Value: {options.MinValue}"); Console.WriteLine($"Max Value: {options.MaxValue}"); Console.WriteLine($"Cyclic: {options.IsCyclic}"); } ``` -------------------------------- ### EnsurePostgresExtension Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/migrations-and-extensions.md Ensures that a PostgreSQL extension is created or installed as part of the migration. This method is chainable and returns the migration builder. ```APIDOC ## EnsurePostgresExtension ### Description Ensures that a PostgreSQL extension is created or installed as part of the migration. ### Method `public static MigrationBuilder EnsurePostgresExtension( this MigrationBuilder builder, string name, string? schema = null, string? version = null) ` ### Parameters #### Path Parameters - **builder** (MigrationBuilder) - Required - The migration builder - **name** (string) - Required - The name of the PostgreSQL extension (e.g., "uuid-ossp", "hstore", "pg_trgm") - **schema** (string?) - Optional - The schema in which the extension is created - **version** (string?) - Optional - The version of the extension to create ### Returns `MigrationBuilder` - The same builder instance so that further operations can be chained. ### Remarks This method creates an `AlterDatabaseOperation` that will be executed during migration. The operation is tracked by EF Core's migration system. ### Example ```csharp protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.EnsurePostgresExtension("uuid-ossp", version: "1.1"); migrationBuilder.EnsurePostgresExtension("pg_trgm"); // Now create tables that depend on these extensions migrationBuilder.CreateTable( name: "Products", columns: table => new { Id = table.Column(nullable: false, defaultValueSql: "uuid_generate_v4()"), Name = table.Column() }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable("Products"); } ``` ``` -------------------------------- ### Get Default Value Generation Strategy Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the default value generation strategy for the entire model. Returns the configured default strategy. ```csharp public static NpgsqlValueGenerationStrategy? GetValueGenerationStrategy( this IReadOnlyModel model) ``` -------------------------------- ### NpgsqlPropertyExtensions - Value Generation Strategy Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Provides methods for getting and setting the value generation strategy for a property. ```APIDOC ## GetValueGenerationStrategy (IReadOnlyProperty) ### Description Gets the value generation strategy configured for this property. ### Method `public static NpgsqlValueGenerationStrategy? GetValueGenerationStrategy(this IReadOnlyProperty property)` ### Returns `NpgsqlValueGenerationStrategy?` - The configured strategy, or null. --- ## SetValueGenerationStrategy (IMutableProperty, NpgsqlValueGenerationStrategy?) ### Description Sets the value generation strategy. ### Method `public static void SetValueGenerationStrategy(this IMutableProperty property, NpgsqlValueGenerationStrategy? strategy)` ### Parameters #### Path Parameters - **property** (IMutableProperty) - Required - The property to configure - **strategy** (NpgsqlValueGenerationStrategy?) - Required - The value generation strategy --- ``` -------------------------------- ### NpgsqlPropertyExtensions - Direct Sequence Configuration Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Provides methods for getting and setting the direct sequence name and schema for a property. ```APIDOC ## GetSequenceName (IReadOnlyProperty) ### Description Gets the name of the direct sequence (non-hi-lo). ### Method `public static string? GetSequenceName(this IReadOnlyProperty property)` --- ## SetSequenceName (IMutableProperty, string?) ### Description Sets the direct sequence name. ### Method `public static void SetSequenceName(this IMutableProperty property, string? name)` ### Parameters #### Path Parameters - **property** (IMutableProperty) - Required - The property to configure - **name** (string?) - Required - The sequence name --- ## GetSequenceSchema (IReadOnlyProperty) ### Description Gets the schema of the direct sequence. ### Method `public static string? GetSequenceSchema(this IReadOnlyProperty property)` --- ## SetSequenceSchema (IMutableProperty, string?) ### Description Sets the schema of the direct sequence. ### Method `public static void SetSequenceSchema(this IMutableProperty property, string? schema)` ### Parameters #### Path Parameters - **property** (IMutableProperty) - Required - The property to configure - **schema** (string?) - Required - The sequence schema --- ``` -------------------------------- ### Get Index Nulls Placement Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Retrieves the nulls placement configuration (NULLS FIRST/NULLS LAST) for each column in the index. Returns null if not explicitly set. ```csharp public static IReadOnlyList? GetNullSortOrder(this IReadOnlyIndex index) { var value = index[NpgsqlIndexExtensions.NullSortOrder]; return value == null ? null : JsonSerializer.Deserialize(value); } ``` -------------------------------- ### Use Repeatable Read Isolation Level for Transactions Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/advanced-scenarios.md Demonstrates how to start a transaction with the Repeatable Read isolation level using EF Core. This ensures that data read within the transaction remains consistent, preventing non-repeatable reads. ```csharp using (var transaction = await dbContext.Database.BeginTransactionAsync( System.Data.IsolationLevel.RepeatableRead)) { try { // Perform operations var orders = await dbContext.Orders .Where(o => o.Status == "pending") .ToListAsync(); // Update orders foreach (var order in orders) { order.Status = "processing"; } await dbContext.SaveChangesAsync(); await transaction.CommitAsync(); } catch { await transaction.RollbackAsync(); throw; } } ``` -------------------------------- ### Ensure PostgreSQL Extension Creation Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/migrations-and-extensions.md This method ensures a PostgreSQL extension is created or installed during a migration. It handles the creation of an `AlterDatabaseOperation` and tracks it within EF Core's migration system. You can specify the extension name, schema, and version. ```csharp protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.EnsurePostgresExtension("uuid-ossp", version: "1.1"); migrationBuilder.EnsurePostgresExtension("pg_trgm"); // Now create tables that depend on these extensions migrationBuilder.CreateTable( name: "Products", columns: table => new { Id = table.Column(nullable: false, defaultValueSql: "uuid_generate_v4()"), Name = table.Column() }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable("Products"); } ``` -------------------------------- ### Get PostgreSQL Index Method Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Retrieves the PostgreSQL index method used for a given index. Valid values include BTREE, HASH, GIN, GIST, and BRIN. ```csharp public static string? GetMethod(this IReadOnlyIndex index) { return (string?)index[NpgsqlIndexExtensions.Method]; } ``` ```csharp var indexMethod = index.GetMethod(); // Possible values: "BTREE", "HASH", "GIN", "GIST", "BRIN" ``` -------------------------------- ### Get PostgreSQL Storage Parameters for Table Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Retrieves PostgreSQL storage parameters for a table, such as FILLFACTOR and AUTOVACUUM settings. Returns the parameter definition string or null if not set. ```csharp public static string? GetStorageParameters(this IReadOnlyEntityType entityType) ``` -------------------------------- ### Get Auto-Generated Sequence Schema Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the schema for auto-generated sequences. ```csharp public static string? GetSequenceSchema(this IReadOnlyModel model) ``` -------------------------------- ### Get Hi-Lo Sequence Schema Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the schema of the hi-lo sequence. ```csharp public static string? GetHiLoSequenceSchema(this IReadOnlyProperty property) ``` -------------------------------- ### Check if Hi-lo Sequence is Explicitly Configured Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Example demonstrating how to check if the Hi-lo sequence name annotation was explicitly configured on a property. This helps differentiate between convention-applied and user-defined settings. ```csharp var hiLoNameAnnotation = property.FindAnnotation(NpgsqlAnnotationNames.HiLoSequenceName); if (hiLoNameAnnotation?.GetConfigurationSource() == ConfigurationSource.Explicit) { Console.WriteLine("Hi-lo sequence explicitly configured"); } ``` -------------------------------- ### Basic EF Core Usage with PostgreSQL Source: https://github.com/npgsql/efcore.pg/blob/main/README.md Demonstrates basic Entity Framework Core operations including database creation, data insertion, and querying using LINQ with the Npgsql provider. Requires a DbContext configuration pointing to a PostgreSQL instance. ```csharp await using var ctx = new BlogContext(); await ctx.Database.EnsureDeletedAsync(); await ctx.Database.EnsureCreatedAsync(); // Insert a Blog ctx.Blogs.Add(new() { Name = "FooBlog" }); await ctx.SaveChangesAsync(); // Query all blogs who's name starts with F var fBlogs = await ctx.Blogs.Where(b => b.Name.StartsWith("F")).ToListAsync(); public class BlogContext : DbContext { public DbSet Blogs { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql(@"Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase"); } public class Blog { public int Id { get; set; } public string Name { get; set; } } ``` -------------------------------- ### Get Hi-Lo Sequence Schema Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the schema of the default hi-lo sequence. ```csharp public static string? GetHiLoSequenceSchema(this IReadOnlyModel model) ``` -------------------------------- ### NpgsqlRetryingExecutionStrategy Constructor with Dependencies and Full Configuration Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Initializes a new instance of the NpgsqlRetryingExecutionStrategy using dependencies and full configuration options. ```csharp public NpgsqlRetryingExecutionStrategy( ExecutionStrategyDependencies dependencies, int maxRetryCount, TimeSpan maxRetryDelay, ICollection? errorCodesToAdd) ``` -------------------------------- ### Core Configuration Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/README.md Entry point configuration methods for setting up PostgreSQL database connections and provider options. Covers `UseNpgsql()` extension methods, `NpgsqlDbContextOptionsBuilder` class, and dependency injection extensions. ```APIDOC ## Core Configuration ### Description Entry point configuration methods for setting up PostgreSQL database connections and provider options. ### Key Methods - `DbContextOptionsBuilder.UseNpgsql(string connectionString, Action?) - `DbContextOptionsBuilder.UseNpgsql(DbConnection connection, bool contextOwnsConnection) - `DbContextOptionsBuilder.UseNpgsql(DbDataSource dataSource) - `NpgsqlDbContextOptionsBuilder.ConfigureDataSource(Action) - `NpgsqlDbContextOptionsBuilder.UseAdminDatabase(string? dbName) - `NpgsqlDbContextOptionsBuilder.SetPostgresVersion(int major, int minor) - `NpgsqlDbContextOptionsBuilder.MapRange(string rangeName) - `NpgsqlDbContextOptionsBuilder.MapEnum(string? enumName) - `NpgsqlDbContextOptionsBuilder.EnableRetryOnFailure() - `IServiceCollection.AddNpgsql(string connectionString) ``` -------------------------------- ### Configure EF Core with NetTopologySuite Source: https://github.com/npgsql/efcore.pg/blob/main/src/EFCore.PG.NTS/README.md Demonstrates how to configure the DbContext to use Npgsql with the NetTopologySuite integration for spatial data. Includes entity definition and basic CRUD operations. ```csharp await using var ctx = new BlogContext(); await ctx.Database.EnsureDeletedAsync(); await ctx.Database.EnsureCreatedAsync(); // Insert a Blog ctx.Cities.Add(new() { Name = "FooCity", Center = new Point(10, 10) }); await ctx.SaveChangesAsync(); // Query all cities with the given center point var newBlogs = await ctx.Cities.Where(b => b.Center == new Point(10, 10)).ToListAsync(); public class BlogContext : DbContext { public DbSet Cities { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql( "@Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase", o => o.UseNetTopologySuite()); } public class City { public int Id { get; set; } public string Name { get; set; } public Point Center { get; set; } } ``` -------------------------------- ### Get Hi-Lo Sequence Name Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the name of the default hi-lo sequence for the model. ```csharp public static string? GetHiLoSequenceName(this IReadOnlyModel model) ``` -------------------------------- ### NpgsqlRetryingExecutionStrategy Constructor with Dependencies Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Initializes a new instance of the NpgsqlRetryingExecutionStrategy using provided execution strategy dependencies. ```csharp public NpgsqlRetryingExecutionStrategy(ExecutionStrategyDependencies dependencies) ``` -------------------------------- ### Get Value Generation Strategy Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the value generation strategy configured for this property. Returns null if not configured. ```csharp public static NpgsqlValueGenerationStrategy? GetValueGenerationStrategy( this IReadOnlyProperty property) ``` -------------------------------- ### NpgsqlRetryingExecutionStrategy Constructor with Full Configuration Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Initializes a new instance of the NpgsqlRetryingExecutionStrategy with full configuration including retry count, delay, and custom error codes. ```csharp public NpgsqlRetryingExecutionStrategy( DbContext context, int maxRetryCount, TimeSpan maxRetryDelay, ICollection? errorCodesToAdd) ``` -------------------------------- ### Get Hi-Lo Sequence Name for Store Object Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the hi-lo sequence name for a specific store object (table). ```csharp public static string? GetHiLoSequenceName( this IReadOnlyProperty property, in StoreObjectIdentifier storeObject) ``` -------------------------------- ### Creating and Querying NpgsqlRange Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/types-and-enums.md Demonstrates how to instantiate NpgsqlRange objects with different bound inclusivities and how to query data using range containment. ```csharp // Create a range [1, 10] var range = new NpgsqlRange(1, 10); // Create a range (1, 10) with exclusive bounds var exclusiveRange = NpgsqlRange.Create(1, false, 10, false); // Query using ranges var result = dbContext.RangeData .Where(r => r.DateRange.Contains(DateTime.Now)) .ToList(); ``` -------------------------------- ### Read Full Property Configuration at Runtime Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Demonstrates how to configure property-specific options like identity columns and their ranges in OnModelCreating, and then read these configurations back at runtime using model introspection. This is useful for verifying or dynamically using configured property behaviors. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .Property(b => b.Id) .UseIdentityByDefaultColumn(seed: 100) .HasIdentityOptions(minValue: 100, maxValue: long.MaxValue); } // Later, read the configuration: var entityType = dbContext.Model.FindEntityType(typeof(Blog)); var idProperty = entityType.FindProperty(nameof(Blog.Id)); var generationStrategy = idProperty.GetValueGenerationStrategy(); var identityOptions = idProperty.GetIdentityOptions(); Console.WriteLine($"Strategy: {generationStrategy}"); Console.WriteLine($"Start: {identityOptions?.StartValue}"); Console.WriteLine($"Min: {identityOptions?.MinValue}"); Console.WriteLine($"Max: {identityOptions?.MaxValue}"); ``` -------------------------------- ### Get Hi-Lo Sequence Name Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the name of the hi-lo sequence for this property. Returns null if not using hi-lo generation. ```csharp public static string? GetHiLoSequenceName(this IReadOnlyProperty property) ``` -------------------------------- ### Configure Covering Index with NpgsqlEFCore Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/migrations-and-extensions.md Create a covering index by including additional properties with `IncludeProperties()` to avoid extra table lookups for common queries. ```csharp modelBuilder.Entity() .HasIndex(o => o.CustomerId) .IncludeProperties(o => o.Total, o => o.CreatedDate); ``` -------------------------------- ### Get Redshift Compatibility Mode Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets whether Redshift compatibility mode is enabled. Returns true if using Redshift; otherwise false. ```csharp public static bool GetUseRedshift(this IReadOnlyModel model) ``` -------------------------------- ### Index Method Configuration Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Configure the PostgreSQL index method (e.g., BTREE, HASH, GIN). ```APIDOC ## GetMethod ### Description Gets the PostgreSQL index method. ### Method `public static string? GetMethod(this IReadOnlyIndex index)` ### Returns `string?` - The index method: "BTREE", "HASH", "GIN", "GIST", "BRIN", or null for default. ### Example ```csharp var indexMethod = index.GetMethod(); // Possible values: "BTREE", "HASH", "GIN", "GIST", "BRIN" ``` ## SetMethod ### Description Sets the index method. Valid values: "BTREE", "HASH", "GIN", "GIST", "BRIN". ### Method `public static void SetMethod(this IMutableIndex index, string? method)` ``` -------------------------------- ### Using NodaTime Types in Entity Framework Core Source: https://github.com/npgsql/efcore.pg/blob/main/src/EFCore.PG.NodaTime/README.md Demonstrates inserting and querying data using NodaTime's Instant type with Entity Framework Core and the Npgsql provider. Ensure your DbContext is configured with UseNodaTime(). ```csharp await using var ctx = new BlogContext(); await ctx.Database.EnsureDeletedAsync(); await ctx.Database.EnsureCreatedAsync(); // Insert a Blog ctx.Blogs.Add(new() { Name = "FooBlog", CreationTime = SystemClock.Instance.GetCurrentInstant() }); await ctx.SaveChangesAsync(); // Query all blogs created in 2020 or after var newBlogs = await ctx.Blogs.Where(b => b.CreationTime >= Instant.FromUtc(2020, 1, 1, 0, 0, 0)).ToListAsync(); ``` -------------------------------- ### GetSequenceSchema Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the schema for auto-generated sequences. ```APIDOC ## GetSequenceSchema ### Description Gets the schema for auto-generated sequences. ### Method GET ### Endpoint NpgsqlModelExtensions.GetSequenceSchema ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string?** - The schema for auto-generated sequences. #### Response Example None ``` -------------------------------- ### GetPostgresVersion Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the target PostgreSQL version for the model. ```APIDOC ## GetPostgresVersion ### Description Gets the target PostgreSQL version for the model. ### Method GET ### Endpoint NpgsqlModelExtensions.GetPostgresVersion ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Version?** - The configured version, or null for default. #### Response Example None ``` -------------------------------- ### Using Index Hints with Raw SQL Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/advanced-scenarios.md When EF Core doesn't directly support query hints, you can leverage raw SQL with FromSqlRaw to include database-specific hints like index hints for performance tuning. ```csharp var result = dbContext.Orders .FromSqlRaw("SELECT /*+ INDEX(orders idx_customer) */ * FROM Orders WHERE customer_id = @id", new NpgsqlParameter("@id", customerId)) .ToList(); ``` -------------------------------- ### Migrations with PostgreSQL Extensions in C# Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/README.md Create migrations that ensure PostgreSQL extensions like 'uuid-ossp' are present and configure table columns with default generated values. ```csharp public partial class AddUuidExtension : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.EnsurePostgresExtension("uuid-ossp"); migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column(nullable: false, defaultValueSql: "uuid_generate_v4()"), Email = table.Column() }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable("Users"); } } ``` -------------------------------- ### GetSequenceNameSuffix Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the suffix appended to generated sequence names. ```APIDOC ## GetSequenceNameSuffix ### Description Gets the suffix appended to generated sequence names. ### Method GET ### Endpoint NpgsqlModelExtensions.GetSequenceNameSuffix ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string?** - The suffix for sequence names. #### Response Example None ``` -------------------------------- ### NpgsqlRetryingExecutionStrategy Constructors Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Provides various constructors for initializing the NpgsqlRetryingExecutionStrategy with different configurations, including DbContext, retry limits, retry delays, and custom error codes. ```APIDOC ## Constructor with DbContext ### Description Initializes the strategy with a DbContext. ### Parameters #### Path Parameters - **context** (DbContext) - Required - The context on which the operations will be invoked. ### Remarks The default retry limit is 6, which means that the total amount of time spent before failing is about a minute. ## Constructor with Dependencies ### Description Initializes the strategy with execution strategy dependencies. ### Parameters #### Path Parameters - **dependencies** (ExecutionStrategyDependencies) - Required - Parameter object containing service dependencies. ## Constructor with MaxRetryCount ### Description Initializes the strategy with a DbContext and a maximum retry count. ### Parameters #### Path Parameters - **context** (DbContext) - Required - The context on which the operations will be invoked. - **maxRetryCount** (int) - Required - The maximum number of retry attempts. ## Constructor with Full Configuration ### Description Initializes the strategy with a DbContext, maximum retry count, maximum retry delay, and additional PostgreSQL error codes. ### Parameters #### Path Parameters - **context** (DbContext) - Required - The context on which the operations will be invoked. - **maxRetryCount** (int) - Required - The maximum number of retry attempts. - **maxRetryDelay** (TimeSpan) - Required - The maximum delay between retries. - **errorCodesToAdd** (ICollection?) - Optional - Additional PostgreSQL error codes that should be considered transient. ## Constructor with Dependencies and Full Configuration ### Description Initializes the strategy with execution strategy dependencies, maximum retry count, maximum retry delay, and additional PostgreSQL error codes. ### Parameters #### Path Parameters - **dependencies** (ExecutionStrategyDependencies) - Required - Parameter object containing service dependencies. - **maxRetryCount** (int) - Required - The maximum number of retry attempts. - **maxRetryDelay** (TimeSpan) - Required - The maximum delay between retries. - **errorCodesToAdd** (ICollection?) - Optional - Additional PostgreSQL error codes that should be considered transient. ``` -------------------------------- ### GetHiLoSequenceSchema Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the schema of the default hi-lo sequence for the model. ```APIDOC ## GetHiLoSequenceSchema ### Description Gets the schema of the default hi-lo sequence for the model. ### Method GET ### Endpoint NpgsqlModelExtensions.GetHiLoSequenceSchema ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string?** - The schema of the hi-lo sequence. #### Response Example None ``` -------------------------------- ### GetHiLoSequenceName Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the name of the default hi-lo sequence for the model. ```APIDOC ## GetHiLoSequenceName ### Description Gets the name of the default hi-lo sequence for the model. ### Method GET ### Endpoint NpgsqlModelExtensions.GetHiLoSequenceName ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string?** - The name of the hi-lo sequence. #### Response Example None ``` -------------------------------- ### Configure GIN Index Method for Full-Text Search and Arrays Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/types-and-enums.md Use the `HasMethod("GIN")` extension to configure GIN indexes, suitable for full-text search on text fields and indexing array elements. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { // Full-text search index modelBuilder.Entity() .HasIndex(d => d.Content) .HasMethod("GIN"); // Array index modelBuilder.Entity() .HasIndex(p => p.Tags) .HasMethod("GIN"); } ``` -------------------------------- ### GetUseRedshift Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets whether Redshift compatibility mode is enabled for the model. ```APIDOC ## GetUseRedshift ### Description Gets whether Redshift compatibility mode is enabled for the model. ### Method GET ### Endpoint NpgsqlModelExtensions.GetUseRedshift ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **bool** - true if using Redshift; otherwise false. #### Response Example None ``` -------------------------------- ### Configure Index Method with NpgsqlEFCore Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/migrations-and-extensions.md Specify a PostgreSQL index method, such as GIN, using `HasMethod()` on the index builder for optimized querying on specific data types. ```csharp modelBuilder.Entity() .HasIndex(d => d.Content) .HasMethod("GIN"); // Generalized Inverted Index ``` -------------------------------- ### GetValueGenerationStrategy Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Gets the default value generation strategy for the entire model. ```APIDOC ## GetValueGenerationStrategy ### Description Gets the default value generation strategy for the entire model. ### Method GET ### Endpoint NpgsqlModelExtensions.GetValueGenerationStrategy ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **NpgsqlValueGenerationStrategy?** - The configured default strategy. #### Response Example None ``` -------------------------------- ### NpgsqlRetryingExecutionStrategy Constructor with DbContext Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Initializes a new instance of the NpgsqlRetryingExecutionStrategy with default retry settings. ```csharp public NpgsqlRetryingExecutionStrategy(DbContext context) ``` -------------------------------- ### Execute Raw SQL with Manual Parameters using EF Core Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/advanced-scenarios.md Use `FromSqlRaw` to execute raw SQL queries with manually created `NpgsqlParameter` objects. This provides more control over parameter types and names. ```csharp var customerId = new NpgsqlParameter("@customerId", 123); var result = await dbContext.Orders .FromSqlRaw("SELECT * FROM Orders WHERE customer_id = @customerId", customerId) .ToListAsync(); ``` -------------------------------- ### NpgsqlPropertyExtensions - Identity Options Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Provides methods for getting and setting PostgreSQL IDENTITY column options for a property. ```APIDOC ## GetIdentityOptions (IReadOnlyProperty) ### Description Gets the PostgreSQL IDENTITY column options for this property. ### Method `public static IdentitySequenceOptionsData? GetIdentityOptions(this IReadOnlyProperty property)` ### Returns `IdentitySequenceOptionsData?` - The identity options if configured, or null. ### Example ```csharp var options = property.GetIdentityOptions(); if (options != null) { Console.WriteLine($"Start Value: {options.StartValue}"); Console.WriteLine($"Increment: {options.IncrementBy}"); Console.WriteLine($"Min Value: {options.MinValue}"); Console.WriteLine($"Max Value: {options.MaxValue}"); Console.WriteLine($"Cyclic: {options.IsCyclic}"); } ``` --- ## SetIdentityOptions (IMutableProperty, IdentitySequenceOptionsData?) ### Description Sets the IDENTITY column options. ### Method `public static void SetIdentityOptions(this IMutableProperty property, IdentitySequenceOptionsData? options)` ### Parameters #### Path Parameters - **property** (IMutableProperty) - Required - The property to configure - **options** (IdentitySequenceOptionsData?) - Required - The identity options --- ``` -------------------------------- ### Configure Npgsql EF Core with Connection String Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Configures the context to connect to a PostgreSQL database using a connection string. An optional action can be provided for additional Npgsql-specific configuration. ```csharp public static DbContextOptionsBuilder UseNpgsql( this DbContextOptionsBuilder optionsBuilder, string? connectionString, Action? npgsqlOptionsAction = null) ``` ```csharp var options = new DbContextOptionsBuilder() .UseNpgsql("Host=localhost;Username=postgres;Password=password;Database=mydb") .Options; ``` -------------------------------- ### UseHiLo - PropertyBuilder Extension (Sequence-based hi-lo) Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/model-builder-extensions.md Configures the property to use a sequence-based hi-lo pattern for value generation. Sets the property to `ValueGenerated.OnAdd`. Defaults to 'hibernate_sequence' if name is not specified. ```csharp public static PropertyBuilder UseHiLo( this PropertyBuilder propertyBuilder, string? name = null, string? schema = null) ``` ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .Property(b => b.Id) .UseHiLo("blog_id_sequence"); } ``` -------------------------------- ### Get PostgreSQL Type OID Information Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/types-and-enums.md Access the Object Identifier (OID) for a PostgreSQL type mapping. ```csharp public static uint? GetTypeOid(this ITypeMapping typeMapping) ``` -------------------------------- ### Get PostgreSQL-Specific Schema Information Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/types-and-enums.md Use this extension method to check if a type base is a PostgreSQL enum. ```csharp public static bool IsPostgresEnum(this ITypeBase typeBase) ``` -------------------------------- ### Configure Unique Index with NpgsqlEFCore Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/migrations-and-extensions.md Use `IsUnique()` on an index builder to create a unique index on a property. Ensure the property is suitable for uniqueness constraints. ```csharp modelBuilder.Entity() .HasIndex(u => u.Email) .IsUnique(); ``` -------------------------------- ### Basic DbContext Configuration in C# Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/README.md Configure a DbContext for PostgreSQL using Npgsql. Ensure the connection string is correctly set and DbSet properties are defined for your entities. ```csharp using Microsoft.EntityFrameworkCore; using Npgsql.EntityFrameworkCore.PostgreSQL; public class BlogContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseNpgsql("Host=localhost;Database=blogs;Username=postgres"); } public DbSet Blogs { get; set; } public DbSet Posts { get; set; } } public class Blog { public int Id { get; set; } public string Name { get; set; } public List Posts { get; set; } } public class Post { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } ``` -------------------------------- ### NpgsqlPropertyExtensions - Hi-Lo Sequence Configuration Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Provides methods for getting and setting the hi-lo sequence name and schema for a property. ```APIDOC ## GetHiLoSequenceName (IReadOnlyProperty) ### Description Gets the name of the hi-lo sequence for this property. ### Method `public static string? GetHiLoSequenceName(this IReadOnlyProperty property)` ### Parameters #### Path Parameters - **property** (IReadOnlyProperty) - Required - The property to check ### Returns `string?` - The sequence name, or null if not using hi-lo generation. --- ## GetHiLoSequenceName (IReadOnlyProperty, StoreObjectIdentifier) ### Description Gets the hi-lo sequence name for a specific store object (table). ### Method `public static string? GetHiLoSequenceName(this IReadOnlyProperty property, in StoreObjectIdentifier storeObject)` ### Parameters #### Path Parameters - **property** (IReadOnlyProperty) - Required - The property to check - **storeObject** (StoreObjectIdentifier) - Required - The store object identifier (table) ### Returns `string?` - The sequence name for the specified store object. --- ## SetHiLoSequenceName (IMutableProperty, string?) ### Description Sets the hi-lo sequence name (use only during model creation). ### Method `public static void SetHiLoSequenceName(this IMutableProperty property, string? name)` ### Parameters #### Path Parameters - **property** (IMutableProperty) - Required - The property to configure - **name** (string?) - Required - The sequence name --- ## SetHiLoSequenceName (IConventionProperty, string?, bool) ### Description Sets the hi-lo sequence name with configuration source tracking. ### Method `public static string? SetHiLoSequenceName(this IConventionProperty property, string? name, bool fromDataAnnotation = false)` ### Parameters #### Path Parameters - **property** (IConventionProperty) - Required - The property to configure - **name** (string?) - Required - The sequence name - **fromDataAnnotation** (bool) - Optional - Whether this came from a data annotation (default: false) ### Returns `string?` - The sequence name. --- ## GetHiLoSequenceSchema (IReadOnlyProperty) ### Description Gets the schema of the hi-lo sequence. ### Method `public static string? GetHiLoSequenceSchema(this IReadOnlyProperty property)` --- ## SetHiLoSequenceSchema (IMutableProperty, string?) ### Description Sets the schema of the hi-lo sequence. ### Method `public static void SetHiLoSequenceSchema(this IMutableProperty property, string? schema)` ### Parameters #### Path Parameters - **property** (IMutableProperty) - Required - The property to configure - **schema** (string?) - Required - The sequence schema --- ``` -------------------------------- ### UseNpgsql - Connection String Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Configures the context to connect to a PostgreSQL database using a connection string. The connection string specifies the host, username, password, and database name. ```APIDOC ## UseNpgsql - Connection String ### Description Configures the context to connect to a PostgreSQL database using a connection string. ### Method `UseNpgsql` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var options = new DbContextOptionsBuilder() .UseNpgsql("Host=localhost;Username=postgres;Password=password;Database=mydb") .Options; ``` ### Response #### Success Response (200) `DbContextOptionsBuilder` - The options builder so that further configuration can be chained. #### Response Example None ``` -------------------------------- ### Set PostgreSQL Backend Version (Major/Minor Integers) Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Use the overload of SetPostgresVersion with major and minor integers to configure the target PostgreSQL backend version. This is an alternative to using a Version object. ```csharp optionsBuilder.UseNpgsql(options => options.SetPostgresVersion(15, 0)); ``` -------------------------------- ### NpgsqlRetryingExecutionStrategy Constructor with MaxRetryCount Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Initializes a new instance of the NpgsqlRetryingExecutionStrategy with a specified maximum retry count. ```csharp public NpgsqlRetryingExecutionStrategy( DbContext context, int maxRetryCount) ``` -------------------------------- ### Get Index Sort Order Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Retrieves the sort order (ASC/DESC) for each column in the index. Returns null if not explicitly configured. ```csharp public static IReadOnlyList? GetSortOrder(this IReadOnlyIndex index) { var value = index[NpgsqlIndexExtensions.SortOrder]; return value == null ? null : JsonSerializer.Deserialize(value); } ``` -------------------------------- ### Get Enum Values for Mapped Enum Type Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/types-and-enums.md Retrieve the string array of values for a mapped enum type property. ```csharp public static string[]? GetEnumValues(this IProperty property) ``` -------------------------------- ### Configure Table with PostgreSQL Schema Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/model-builder-extensions.md Use this method to specify both the table name and the PostgreSQL schema for an entity type. Ensure the schema exists in your database. ```csharp public static EntityTypeBuilder ToTable( this EntityTypeBuilder entityTypeBuilder, string name, string schema) ``` ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .ToTable("blogs", schema: "public"); } ``` -------------------------------- ### Configure DbContext with NodaTime Support Source: https://github.com/npgsql/efcore.pg/blob/main/src/EFCore.PG.NodaTime/README.md Add the UseNodaTime() extension method to your Npgsql options in OnConfiguring to enable NodaTime support. This allows NodaTime types to be used in your entity properties. ```csharp public class BlogContext : DbContext { public DbSet Blogs { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql( "@Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase", o => o.UseNodaTime()); } public class Blog { public int Id { get; set; } public string Name { get; set; } public Instant CreationTime { get; set; } } ``` -------------------------------- ### Get Index Collation Rules Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Retrieves the collation rules applied to each column within the index. Returns null if not explicitly set. ```csharp public static IReadOnlyList? GetCollation(this IReadOnlyIndex index) { var value = index[NpgsqlIndexExtensions.Collation]; return value == null ? null : JsonSerializer.Deserialize(value); } ``` -------------------------------- ### Execute Raw SQL with NpgsqlDatabaseFacadeExtensions Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/migrations-and-extensions.md Use this method to execute arbitrary SQL commands directly against the database. Supports parameterized queries to prevent SQL injection. ```csharp public static IExecutionResult ExecuteRawAsync( this DatabaseFacade databaseFacade, string sql, params object?[] parameters) ``` ```csharp await dbContext.Database.ExecuteRawAsync( "CREATE INDEX idx_username ON users(username)"); ``` ```csharp await dbContext.Database.ExecuteRawAsync( "INSERT INTO logs (message, timestamp) VALUES (@p0, @p1)", "Application started", DateTime.UtcNow); ``` -------------------------------- ### UseNpgsql - No Connection Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Configures the context to connect to a PostgreSQL server without initially setting a connection or connection string. The connection must be set before the DbContext is used via `RelationalDatabaseFacadeExtensions.SetDbConnection` or `RelationalDatabaseFacadeExtensions.SetConnectionString`. ```APIDOC ## UseNpgsql - No Connection ### Description Configures the context to connect to a PostgreSQL server without initially setting a connection or connection string. The connection must be set before the DbContext is used via `RelationalDatabaseFacadeExtensions.SetDbConnection` or `RelationalDatabaseFacadeExtensions.SetConnectionString`. ### Method `UseNpgsql` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var options = new DbContextOptionsBuilder() .UseNpgsql(npgsqlOptions => npgsqlOptions.SetPostgresVersion(15, 0)) .Options; ``` ### Response #### Success Response (200) `DbContextOptionsBuilder` - The options builder so that further configuration can be chained. #### Response Example None ``` -------------------------------- ### Get Name of Foreign Key Constraint Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Retrieves the name of the foreign key constraint as it is defined in the database. This allows for precise identification of the constraint. ```csharp public static string? GetConstraintName(this IReadOnlyForeignKey foreignKey) ``` -------------------------------- ### Get Custom Index Operators Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Retrieves the list of custom operator names configured for an index. Returns null if no custom operators are set. ```csharp public static IReadOnlyList? GetOperators(this IReadOnlyIndex index) { var value = index[NpgsqlIndexExtensions.Operators]; return value == null ? null : JsonSerializer.Deserialize(value); } ``` -------------------------------- ### Configure Hi-Lo Sequence for Value Generation Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/README.md Configure the Hi-Lo sequence for identity value generation at the model level using UseHiLo. Specify the sequence name and schema. ```csharp ModelBuilder.UseHiLo(string? name = null, string? schema = null) ``` -------------------------------- ### Get Database Name of Key Constraint Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Retrieves the specific name assigned to a database key constraint. This is useful for direct database interaction or referencing. ```csharp public static string? GetName(this IReadOnlyKey key) ``` -------------------------------- ### Configure Npgsql Data Source Options Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/README.md Configure advanced Npgsql data source options using ConfigureDataSource with NpgsqlDataSourceBuilder. This allows for fine-grained control over connection pooling and other settings. ```csharp NpgsqlDbContextOptionsBuilder.ConfigureDataSource(Action configure) ``` -------------------------------- ### Perform Full-Text Search Queries Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/advanced-scenarios.md Execute full-text search queries using FromSqlInterpolated or FromSqlRaw. The latter allows for parameterization and ranking. ```csharp var results = dbContext.Articles .FromSqlInterpolated($@"SELECT * FROM Articles WHERE SearchVector @@ to_tsquery({query})") .ToList(); ``` ```csharp // Or using raw query with ranking var ranked = dbContext.Articles .FromSqlRaw(@"SELECT a.*, ts_rank(a.SearchVector, q.query) AS rank FROM Articles a, to_tsquery('english', @query) q(query) WHERE a.SearchVector @@ q.query ORDER BY rank DESC", new NpgsqlParameter("@query", searchTerm)) .ToList(); ``` -------------------------------- ### Get Configuration Source of an Annotation Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Use this extension method to determine how a specific annotation was applied to a property. Useful for debugging configuration conflicts or understanding applied conventions. ```csharp public static ConfigurationSource? GetConfigurationSource(this IAnnotation annotation) ``` -------------------------------- ### Reading Runtime Metadata in C# Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/README.md Access and inspect EF Core model metadata at runtime, including value generation strategies, identity options, and index configurations. ```csharp var model = dbContext.Model; var entityType = model.FindEntityType(typeof(Blog)); var idProperty = entityType.FindProperty(nameof(Blog.Id)); // Check value generation strategy var strategy = idProperty.GetValueGenerationStrategy(); Console.WriteLine($"Strategy: {strategy}"); // Check IDENTITY options var identityOptions = idProperty.GetIdentityOptions(); if (identityOptions != null) { Console.WriteLine($"Start: {identityOptions.StartValue}"); Console.WriteLine($"Min: {identityOptions.MinValue}"); } // Check index configuration var index = entityType.GetIndexes().FirstOrDefault(); if (index != null) { Console.WriteLine($"Index Method: {index.GetMethod()}"); Console.WriteLine($"Collation: {index.GetCollation()}"); } ``` -------------------------------- ### Configure PostgreSQL Connection with Npgsql Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/README.md Use the UseNpgsql extension method on DbContextOptionsBuilder to configure the PostgreSQL connection. Overloads support connection strings, existing DbConnection objects, or DbDataSource. ```csharp DbContextOptionsBuilder.UseNpgsql(string connectionString, Action? optionsAction = null) ``` ```csharp DbContextOptionsBuilder.UseNpgsql(DbConnection connection, bool contextOwnsConnection = true, Action? optionsAction = null) ``` ```csharp DbContextOptionsBuilder.UseNpgsql(DbDataSource dataSource, Action? optionsAction = null) ``` -------------------------------- ### Get Included Properties for Covering Index Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Retrieves the list of non-key properties included in a covering index. Returns null if the index is not a covering index or properties are not set. ```csharp public static IReadOnlyList? GetIncludeProperties(this IReadOnlyIndex index) { var value = index[NpgsqlIndexExtensions.IncludeProperties]; return value == null ? null : JsonSerializer.Deserialize(value); } ``` -------------------------------- ### Set PostgreSQL Backend Version (Version Object) Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/core-configuration.md Use SetPostgresVersion with a Version object to configure the target PostgreSQL backend version. This is required for certain features. ```csharp optionsBuilder.UseNpgsql(options => options.SetPostgresVersion(new Version(15, 0))); ``` -------------------------------- ### Get Unlogged Table Status Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/metadata-extensions.md Checks if a table is configured as unlogged, which offers faster performance but sacrifices crash safety. Returns true if the table is unlogged, false otherwise. ```csharp public static bool GetIsUnlogged(this IReadOnlyEntityType entityType) ``` -------------------------------- ### Register Npgsql for Dependency Injection Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/README.md Register the Npgsql EF Core provider with the dependency injection container using AddNpgsql. This is typically done in the application's startup configuration. ```csharp IServiceCollection.AddNpgsql(string connectionString, Action? optionsAction = null) ``` -------------------------------- ### Map JSON Columns in Entity Framework Core Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/advanced-scenarios.md Define entity properties with the 'jsonb' type to map JSON columns in your database. This example shows mapping a JsonDocument and a Dictionary. ```csharp public class Document { public int Id { get; set; } public string Title { get; set; } [Column(TypeName = "jsonb")] public JsonDocument Content { get; set; } [Column(TypeName = "jsonb")] public Dictionary Metadata { get; set; } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .Property(d => d.Content) .HasColumnType("jsonb"); modelBuilder.Entity() .Property(d => d.Metadata) .HasColumnType("jsonb"); } ``` -------------------------------- ### Configure HiLo Value Generation Strategy Source: https://github.com/npgsql/efcore.pg/blob/main/_autodocs/model-builder-extensions.md Configures the model to use a sequence-based hi-lo pattern for generating values. The hi-lo pattern uses a database sequence and a high/low algorithm to batch allocate IDs. If the sequence does not exist, it will be created. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.UseHiLo("id_sequence", schema: "public"); } ```