GithubHelp home page GithubHelp logo

giorgi / entityframework.exceptions Goto Github PK

View Code? Open in Web Editor NEW
1.1K 17.0 63.0 226 KB

Handle database errors easily when working with Entity Framework Core. Supports SQLServer, PostgreSQL, SQLite, Oracle and MySql.

Home Page: https://giorgi.dev/entity-framework/introducing-entityframework-exceptions/

License: Other

C# 100.00%
entity-framework-core netcore2 sql-server postgresql mysql netcore3 database-exceptions sqlite sqlite3 entityframework

entityframework.exceptions's Introduction

Hi there ๐Ÿ‘‹ I'm Giorgi

Twitter Follow Website Hire Giorgi Sponsor Giorgi

I am a software developer with more than a decade of experience, working mainly with C#, ASP.NET Core, REST, GraphQL, MAUI, Xamarin, Entity Framework Core, AWS, Azure, and SQL Server. I have also worked with many other frameworks and systems such as ASP.NET MVC, ASP.NET Web API, WCF, Avalonia, WinForms, Oracle, and many more. Top 1% on Stack Overflow, member of Top 3% freelance software developers network and InfoQ Editor.

Check out my portfolio or read my blog and Follow me on Twitter and Follow me on InfoQ

GitHub Streak

Shows an illustrated sun in light mode and a moon with stars in dark mode. Shows an illustrated sun in light mode and a moon with stars in dark mode.

entityframework.exceptions's People

Contributors

aerion avatar anoordover avatar bgaprogrammer avatar codymullins avatar dependabot[bot] avatar giorgi avatar jerone avatar johnavery avatar selmirrrrr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

entityframework.exceptions's Issues

PooledDbContext

Hello.

I ran into the problem of adding this library when using a context pool.

Registration:

builder.Services.AddPooledDbContextFactory<ApplicationContext>(options => options.UseNpgsql(connectionString));

public class ApplicationContext : DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options)
        : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseExceptionProcessor();
    }
}

Error:
Unhandled exception. System.InvalidOperationException: 'OnConfiguring' cannot be used to modify DbContextOptions when DbContext pooling is enabled.

The certificate chain was issued by an authority that is not trusted.

I have added EntityFrameworkCore.Exceptions.SqlServer 6.0.3 to my working Worker Project that uses EFCore 6.0.7 and as soon as I do so, I can no longer run my project. Adding the following does not make it work either.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseExceptionProcessor();
    }

The only way to fix the connection to my database is to remove the Nuget. Simply having it installed in my project breaks connections to SQLServer. If I copy the files from this project into my project directly for SqlServer, then it works. So something about the nuget is causing issues. I have repeated this test 10 times now, consistently with the following results. Why does this nugget break the connection?

Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database 'TicketDatabase' on server 'server.lan'.
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'ZenTool.Worker.Data.ZenToolContext'.
      Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
       ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock)
         at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
         at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
         at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOp
tions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
         at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
      ClientConnectionId:9f240911-6978-430f-8f6f-55d08fe48d48
      Error Number:-2146893019,State:0,Class:20
      Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
       ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock)
         at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
         at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
         at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOp
tions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
         at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
      ClientConnectionId:9f240911-6978-430f-8f6f-55d08fe48d48
      Error Number:-2146893019,State:0,Class:20
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock)
   at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
   at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
   at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions,
 SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at ZenTool.Worker.Repository.ZenToolRepository.CountFields() in P:\Apps\ZenTool\ZenTool.Worker\Repository\ZenToolRepository.cs:line 31
   at ZenTool.Worker.Worker.ExecuteAsync(CancellationToken stoppingToken) in P:\Apps\ZenTool\ZenTool.Worker\Worker.cs:line 37
ClientConnectionId:9f240911-6978-430f-8f6f-55d08fe48d48
Error Number:-2146893019,State:0,Class:20
fail: Microsoft.Extensions.Hosting.Internal.Host[9]
      BackgroundService failed
      Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
       ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock)
         at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
         at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
         at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOp
tions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
         at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
         at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
         at ZenTool.Worker.Repository.ZenToolRepository.CountFields() in P:\Apps\ZenTool\ZenTool.Worker\Repository\ZenToolRepository.cs:line 31
         at ZenTool.Worker.Worker.ExecuteAsync(CancellationToken stoppingToken) in P:\Apps\ZenTool\ZenTool.Worker\Worker.cs:line 37
         at Microsoft.Extensions.Hosting.Internal.Host.TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)
      ClientConnectionId:9f240911-6978-430f-8f6f-55d08fe48d48
      Error Number:-2146893019,State:0,Class:20
crit: Microsoft.Extensions.Hosting.Internal.Host[10]
      The HostOptions.BackgroundServiceExceptionBehavior is configured to StopHost. A BackgroundService has thrown an unhandled exception, and the IHost instance is stopping. To avoid this behavior, configure this to Ignore; however the BackgroundService will not be restarted.
      Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
       ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock)
         at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
         at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
         at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOp
tions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
         at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
         at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
         at ZenTool.Worker.Repository.ZenToolRepository.CountFields() in P:\Apps\ZenTool\ZenTool.Worker\Repository\ZenToolRepository.cs:line 31
         at ZenTool.Worker.Worker.ExecuteAsync(CancellationToken stoppingToken) in P:\Apps\ZenTool\ZenTool.Worker\Worker.cs:line 37
         at Microsoft.Extensions.Hosting.Internal.Host.TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)
      ClientConnectionId:9f240911-6978-430f-8f6f-55d08fe48d48
      Error Number:-2146893019,State:0,Class:20

not working for me

@Giorgi
Hi, Thank you for your hard work.
unfortunately, this is working for me.
I am using .net core 3.1 with MySql
could you please help to use this package.
I have installed these package along with your package.
EntityFrameworkCore.Exceptions.MySql
EntityFrameworkCore.Exceptions.MySql.Pomelo
but it not working.
one more important thing I am customizing identity classes that why I am using DB context like this way
public class ApplicationDbContext: IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
public DbSet ApplicationUsers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseExceptionProcessor();
}
public ApplicationDbContext(DbContextOptions options) : base(options)
{

    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new PhotoConfiguration());
        modelBuilder.ApplyConfiguration(new XERideServicesConfiguration());
        modelBuilder.ApplyConfiguration(new XERideServicesSettingsConfiguration());
        modelBuilder.ApplyConfiguration(new RideRequestConfiguration());
        modelBuilder.ApplyConfiguration(new RideRequestDetailConfiguration());
        modelBuilder.ApplyConfiguration(new ComplainsConfiguration());
        modelBuilder.ApplyConfiguration(new ApplicationUserConfiguration());
        modelBuilder.ApplyConfiguration(new NotificationConfiguration());
        modelBuilder.ApplyConfiguration(new NotificationDetailConfiguration());
        modelBuilder.ApplyConfiguration(new FileConfiguration());
        modelBuilder.ApplyConfiguration(new BaseFaresConfiguration());
        base.OnModelCreating(modelBuilder);
    }

    public override int SaveChanges()
    {
        this.AuditEntities();
        return base.SaveChanges();
    }

    
    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        this.AuditEntities();

        return await base.SaveChangesAsync(cancellationToken);
    }
}

Strong-named assembly

Warning CS8002 Referenced assembly 'EntityFramework.Exceptions.SqlServer, Version=6.0.3.0, Culture=neutral, PublicKeyToken=null' does not have a strong name.
Warning CS8002 Referenced assembly 'EntityFramework.Exceptions.Common, Version=6.0.3.0, Culture=neutral, PublicKeyToken=null' does not have a strong name.

ExceptionProcessorInterceptor Throws Exception

Hello,

Thank you so much for your efforts on this project. ๐Ÿ™

I seem to be experiencing an exception with this line here:

https://github.com/Giorgi/EntityFramework.Exceptions/blob/main/EntityFramework.Exceptions.Common/ExceptionProcessorInterceptor.cs#L94

In my case I have an abstract class that serves as the table for the hierarchy of implementations. It appears it's going through each of the implementations and repeating the abstract class as the index owner, as seen here in the results from the debugger:

image

This results in the following exception:

System.ArgumentException: An item with the same key has already been added. Key: IX_CreationReason_DisbursementAccountId
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector)
   at EntityFramework.Exceptions.Common.ExceptionProcessorInterceptor`1.SetConstraintDetails(DbContext context, UniqueConstraintException exception, Exception providerException)
   at EntityFramework.Exceptions.Common.ExceptionProcessorInterceptor`1.SaveChangesFailedAsync(DbContextErrorEventData eventData, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Diagnostics.CoreLoggerExtensions.SaveChangesFailedAsync(IDiagnosticsLogger`1 diagnostics, DbContext context, Exception exception, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)

Please let me know if there is any further information I can provide and I will assist.

Db content isn't cleared between each test

Steps to reproduce:

  • in DatabaseTests.cs, add the two following tests Test1 and Test2
        [Fact]
        public virtual void Test1()
        {
            Assert.Equal(0, Context.Products.Count());
            Context.Products.Add(new Product {Name = "Foo"});
            Context.SaveChanges();
        }

        [Fact]
        public virtual void Test2()
        {
            Assert.Equal(0, Context.Products.Count());
            Context.Products.Add(new Product {Name = "Foo"});
            Context.SaveChanges();
        }
  • run both tests (not each one individually, but select those two tests and run them)

Expected result: the two tests should pass
Actual result: one test passes, the other one fails

Assert.Equal() Failure
Expected: 0
Actual:   1

Release on NuGet

I am more likely to use your software if it is released as a nuget package :)

racker

Sorry accidently created while searching. You can delete this issue.

EF Core 5.0 support

Do you plan to support EF Core 5 which was release a couple of weeks ago?

Implement DbException-translator

The current implementation uses the EF StateManager to intercept SaveChanges and SaveChangesAsync.
I think it would be nice to provide an entry-point to use the different ExceptionProcessorStateManagers as a translator for a DbException so that a user can also use these translators in their own catch-block to translate a DbException or a DbUpdateException to specific exception.
These translators can than be used in a catch-block when executing e.g. ExecuteSqlInterpolatedAsync.
When translating from a DbException these translators don't need a dependency on any specific EF-version.

8.0.0.1 Nuget package compilation issue

There appears to be a packaging issue with the latest nuget release 8.0.0.1: The names of the DLL and PDB files are not correct

After running a nuget update, many tests started to fail with the message:
image

I looked through the downloaded package and saw the following, which appears to be incorrectly named files:

image

I then looked in my VS dependency list and see this:

image

Release new Nuget Sqlite version

Hello,

#14 was merged on master April 12th and the last release of the nuget package is from April 9th.
Could you release a new nuget version of the package so that this change is taken into account?

Thanks!

Code vulnerabilities in old SqlClient package

The version 4.1.0 of Microsoft.Data.SqlClient is being marked as containing vulnerabilities in one of his transitive dependencies. A quick fix is just to upgrade it to the current latest 5.1.1 in the SqlServer wrapper.

Need to update MySQLConnector to 1.0.0 when using Net 5 and Pomelo

Version: 3.1.2

Entity Framework Core 5.0.0

When using the MySQL.Pomelo exception helpers I needed to update the MySQLConnector package to 1.0.0 or it would throw a TypeLoadException.

System.TypeLoadException: Could not load type 'MySql.Data.MySqlClient.MySqlException' from assembly 'MySqlConnector, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d33d3e53aa5f8c92'. at EntityFramework.Exceptions.MySQL.Pomelo.ExceptionProcessorExtensions.UseExceptionProcessor(DbContextOptionsBuilder self) at Hive.Web.API.Models.DatabaseContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in C:\Users\weird\source\repos\Hive.Web.API\Hive.Web.API\Models\DatabaseContext.cs:line 41

[Question] how to suppress log messages from EF-Core

Hi Giorgi,

first of all, thanks for your work, i really like this lib.

Its just a side question which i guess is more concern of ef-core, anyway:

Im working with postgres and i have this usecase:


    try
        {
            dbContext.SaveChanges();
        }

        catch (UniqueConstraintException)
        {
            //.... resolve task
            dbContext.SaveChanges();
        }

At the moment of the catch clause EF-Core already has written already a log message:

fail: Microsoft.EntityFrameworkCore.Update[10000]
      An exception occurred in the database while saving changes for context type

Is there any possbility to supress this kind of messages?

EntityFrameworkCore.Exceptions.SqlServer has breaking change released as revision

EntityFrameworkCore.Exceptions.SqlServer 6.0.3.2 increases the dependency on Microsoft.Data.SqlClient from 4.1.0 to 5.1.1.

According to semantic versioning, this would mean that EntityFrameworkCore.Exceptions.SqlServer has to also be a major release. And exactly that just broke our software.

One part of the software updated from 6.0.3.1 to 6.0.3.2 while another module (pre-compiled) was still on 6.0.3.1, getting the newer SqlClient as transitive dependency and having the Encrypt property of the SqlConnectionStringBuilder fail only at runtime. Since there are no upper limits defined in the dependencies, no warning will be issued on creating the top-level project referencing those.

Please try to follow semantic versioning guidelines to avoid issues for other developers. I would advise to re-release as 7.0.0 and de-list the version from NuGet to not break others as well.

Using library with AddDbContextPool

Hi, is it possible to use this library with AddDbContextPool method on startup? It gives me
''OnConfiguring' cannot be used to modify DbContextOptions when DbContext pooling is enabled.'
when trying to use it with pooling

Add ability to use without Inheritance

If you are using something like IdentityDbContext, then multiple inheritance with this would not work. Please consider adding the ability to wire this up on initialization/configuration.

Thanks

SaveChangesAsync

So after trying out this package and looking at the code, this doesn't work for SaveChangeAsync right? Would it take much work to add this?

Trusted certificate issue when package installed but not used

Once I installed the package (SqlServer) to my .NET 6 API project and added the call to UseExceptionProcessor() when configuring my DbContext, I ran into an issue with my connection, saying:

A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)

Adding the TrustServerCertificate=True to my connection string solved the issue.

However, when I commented out the UseExceptionProcessor() call and removed the TrustServerCertificate=True portion from the connection string, the error still occurred.

Only once I uninstalled the package from the project did it resolve itself. What all is the package doing when installed but not setup to run? Shouldn't it not be doing anything differently?

Possible issue in Sqlite unique constraint error handling

Libraries
Microsoft.EntityFrameworkCore.Sqlite 6.0.6
EntityFrameworkCore.Exceptions.Sqlite Version 6.0.3

I have a simple asp.net project correctly configured for exceptions

builder.Services.AddDbContext<NorthwindContext>(o =>
{
    o.EnableSensitiveDataLogging();
    o.UseSqlite("data source=northwind.db");
    o.UseExceptionProcessor();
});

I have the Customers table with a CustomerId primary key and the Orders table with a CustomerId foreign key. When I try to delete a customer with associated orders, the operation obviously fails. The SqliteErrorCode is 19 and SqliteExtendedErrorCode is 1811.

The problem is the SqliteExceptionProcessorInterceptor class doesn't handle the 1811 value in the switch, therefore in my code I receive a DbUpdateException and not a ReferenceConstraintException. Should the 1811 (const SQLITE_CONSTRAINT_TRIGGER) value be included in the switch?

EF6 Support

While EntityFramework.Core is maturing, not everyone is ready to leave EntityFramework 6. But I figure much of the implementation would be the same.

Add reference constraint support for sql server

It would be nice to add support for error 547 in sql server which is a reference constraint error. I created a pull request for you to review the new feature and if approved update the nuget package.

ExceptionProcessorContext?

I downloade the SqlServer package but cannot find the ExceptionProcessorContext. This class is missing in the EntityFramework.Exceptions.Common.

No easy way to determine which constraint failed.

Problem

When entity has more than one constraint there is no easy way to dermine which constraint failed. You need to resort to underlying DB provider exception, which slightly defies the idea behind this library of having high-level exception handling.

Currently you need to do it like that:

   // Both username/email are required to be unique
    var user = new User
    {
        Username = username,
        Email = email,
    };

    await _dbContext.AddAsync(user);

    try
    {
        await _dbContext.SaveChangesAsync();
    }
    catch (UniqueConstraintException e)
    {
        if(e.InnerException is PostgresException pge)
        {
            if(pge.ConstraintName == "IX_User_Email")
            {
               //Unique email constraint failes
            }
            else if(pge.ConstraintName == "IX_User_Username")
            {
               //Unique username constraint failes
            }
        }
    }

Proposal

Add fields to the exception to hold additional information like name of the constraint that failed. DB Providers typically contain that in their exceptions, so it's only a matter of mapping them to classes like UniqueConstraintException

That would include:

    public string ConstraintName { get; }
    public string DataTypeName { get; }
    public string ColumnName { get; }
    public string TableName { get; }
    public string SchemaName { get; }

This would simplify the catch block like that:

   // Both username/email are required to be unique
    var user = new User
    {
        Username = username,
        Email = email,
    };

    await _dbContext.AddAsync(user);

    try
    {
        await _dbContext.SaveChangesAsync();
    }
    catch (UniqueConstraintException e)
    {
        if(e.ConstraintName == "IX_User_Email")
        {
           //Unique email constraint failes
        }
        else if(e.ConstraintName == "IX_User_Username")
        {
           //Unique username constraint failes
        }
    }

I can provide a PR if you approve.

MySql exceptions not working

Thank you for your nice package.
but on my side, it is not working
here is my startup class configuration
var connection = Startup.Configuration["Data:xeride_db"];
options.UseMySql(connection, b =>
{
b.MigrationsAssembly("XERide.API");
}).UseExceptionProcessor();

Account controller create user method
try
{
IdentityResult result = await _userManager.CreateAsync(user, model.Password);
}
catch (UniqueConstraintException e)
{
return BadRequest(e.Message);
//Handle exception here
}

I can't catch exception control goes out before reach to catch block.
any direction sir.

I also visited your MySQL server test class and try to configure

Log question

I use Serilog to log EntityFramework exceptions, but using this library I would like to exclude e.g. EntityFramework.Exceptions.Common.UniqueConstraintException

What is a best practice?

Thanks

How can one use UseExceptionProcessor in code targetting multiple databases?

In Startup.cs I have

        if (isPostGres)
        {
            services.AddDbContext<CprDbContext>(options => options
                .UseNpgsql(connection, x => x.UseNetTopologySuite())
                .UseExceptionProcessor(options);
            );
        }
        else
        {
            services.AddDbContext<CprDbContext>(options => options
                .UseSqlServer(connection, x => x.UseNetTopologySuite())
                .UseExceptionProcessor(options)
                );
        }

Obviously, this gives:

The call is ambiguous between the following methods or properties: 'EntityFramework.Exceptions.PostgreSQL.ExceptionProcessorExtensions.UseExceptionProcessor(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder)' and 'EntityFramework.Exceptions.SqlServer.ExceptionProcessorExtensions.UseExceptionProcessor(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder)' 

I could use AddInterceptors() rather than UseExceptionProcessor() if the interceptors were public, but since they aren't, how can I manage to accomplish this for a database determined purely by its connection string?

Cannot use extension optionsBuilder.UseExceptionProcessor()

Hello,
I wanted to use EntityFrameworkCore.Exceptions.SqlServer package version 3.1.4 in my project but the extension method optionsBuilder.UseExceptionProcessor() cannot be used when using entity framework in more advanced way.

I'm configuring EF with UseInternalServiceProvider(IServiceProvider).

In this case the self.ReplaceService<IStateManager, SqlServerExceptionProcessorStateManager>() cannot be used, but I need to register it to service collection as scoped service like services.AddScoped<IStateManager, SqlServerExceptionProcessorStateManager>().

The problem is that there is no extension method to do it and the SqlServerExceptionProcessorStateManager is not public.

Could you either make SqlServerExceptionProcessorStateManager public or provide some extension method?
For example OracleExceptionProcessorStateManager is already public.

Thank you and have a great day!

Get Exception returns all DB context entries, which cause huge log file. and vulnerable to add modified, added data

Hi,

I received huge log file when DBUpdateException raised. Exception details added Entries of entire DB context along with Models and its attributes. As I am logging complete exception, single log produced 6Mb file.

I found following code in EntityFramework.Exceptions.Common might causing it

private Exception GetException(DbUpdateException ex)
{
    T val = ex.GetBaseException() as T;
 if (val != null)
 {
     DatabaseError? databaseError = GetDatabaseError(val);
    if (databaseError.HasValue)
    {
        DatabaseError valueOrDefault = databaseError.GetValueOrDefault();
        List entries = ex.Entries.Select((EntityEntry entry) => base.GetOrCreateEntry(entry.Entity, entry.Metadata)).ToList();
        return ExceptionFactory.Create(valueOrDefault, ex, entries);
    }
 }
        return null;
 }

Include provider and version information
EntityFrameworkCore.Exceptions.SqlServer 3.1.4
EF Core version: 5.0.13
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (e.g. .NET 5.0)
Operating system:
IDE: (e.g. Visual Studio 2022 17.0.6)

Support for the CosmosDB provider

Is there any work regarding a version of this library for the CosmosDB provider?

I ran into a situation today where I needed to handled the DbUpdateException and after some searching, found out about this library. However, I'm using the Cosmos provider, which doesn't appear to be supported at the moment.

MaxLengthExceededException not being thrown when using SQL Server 2019

Hello, I just integrated your library into my code, and to test, I attempted to produce a MaxLengthExceededException by setting a 32 character field to 33 characters. To my surprise, instead of catching a MaxLengthExceededException, I instead caught a plain-old DbUpdateException.

I viewed the code in SqlServerExceptionProcessorInterceptor, and I see that you are matching that exception up with error 8152, but for SQL Server 2019, that error code has been replaced by 2628 (see: String or Binary data would be truncated: replacing the infamous error 8152).

Can you please update the package such that it would treat either code as a MaxLengthExceededException? For now I can workaround by inspecting the error number manually. Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.