Skip to content

Commit

Permalink
Fixes EFCore crash when using PostgreSQL without `Persist Security In…
Browse files Browse the repository at this point in the history
…fo = true`. #1643
  • Loading branch information
yang-xiaodong committed Feb 4, 2025
1 parent a57dce5 commit 86b5f95
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/DotNetCore.CAP.PostgreSql/CAP.PostgreSqlOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Linq;
using DotNetCore.CAP.Internal;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Npgsql;
Expand All @@ -18,7 +20,7 @@ public class PostgreSqlOptions : EFOptions
/// </summary>
[Obsolete("Use .DataSource = NpgsqlDataSource.Create(<connectionString>) for same behavior.")]
public string ConnectionString { get; set; } = default!;

/// <summary>
/// Gets or sets the Npgsql data source that will be used to store database entities.
/// </summary>
Expand Down Expand Up @@ -55,10 +57,15 @@ public void Configure(PostgreSqlOptions options)
using var scope = _serviceScopeFactory.CreateScope();
var provider = scope.ServiceProvider;
using var dbContext = (DbContext)provider.GetRequiredService(options.DbContextType);
var connectionString = dbContext.Database.GetConnectionString();
if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(connectionString);

var coreOptions = dbContext.GetService<IDbContextOptions>();
var extension = coreOptions.Extensions.First(x => x.Info.IsDatabaseProvider);
options.DataSource = extension.GetType().GetProperty(nameof(options.DataSource))?.GetValue(extension) as NpgsqlDataSource;
if (options.DataSource == null)
{
#pragma warning disable CS0618 // Type or member is obsolete
options.ConnectionString = connectionString;
options.ConnectionString = extension.GetType().GetProperty(nameof(options.ConnectionString))?.GetValue(extension) as string;
#pragma warning restore CS0618 // Type or member is obsolete
}
}
}

0 comments on commit 86b5f95

Please sign in to comment.