Other
PostgreSQL extensions
The Npgsql EF Core provider allows you to specify PostgreSQL extensions that should be set up in your database.
Simply use HasPostgresExtension
in your context's OnModelCreating
method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.HasPostgresExtension("hstore");
Execution Strategy
The Npgsql EF Core provider provides a retrying execution strategy, which will attempt to detect most transient PostgreSQL/network errors and will automatically retry your operation. To enable, place the following code in your context's OnModelConfiguring
:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseNpgsql(
"<connection_string>",
options => options.EnableRetryOnFailure());
This strategy relies on the IsTransient
property of NpgsqlException
.
Certificate authentication
The Npgsql allows you to provide a callback for verifying the server-provided certificates, and to provide a callback for providing certificates to the server. The latter, if properly set up on the PostgreSQL side, allows you to do client certificate authentication - see the Npgsql docs and also the PostgreSQL docs on setting this up.
The Npgsql EF Core provider allows you to set these two callbacks on the DbContextOptionsBuilder
as follows:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseNpgsql(
"<connection_string>",
options =>
{
options.RemoteCertificateValidationCallback(MyCallback1);
options.ProvideClientCertificatesCallback(MyCallback2);
});
You may also consider passing Trust Server Certificate=true
in your connection string to make Npgsql accept whatever certificate your PostgreSQL provides (useful for self-signed certificates).
Caution
When specifying the options via OnConfiguring
, make sure that the callbacks you pass in are static methods. Passing in instance methods causes EF Core to create a new service provider for each context instance, which can degrade performance in a significant way.
CockroachDB Interleave In Parent
If you're using CockroachDB, the Npgsql EF Core provider exposes its "interleave in parent" feature. Use the following code:
protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<Customer>()
.UseCockroachDbInterleaveInParent(
typeof(ParentEntityType),
new List<string> { "prefix_column_1", "prefix_column_2" });