File tree Expand file tree Collapse file tree
Open diff view settings
Expand file tree Collapse file tree
Open diff view settings
Original file line number Diff line number Diff line change @@ -183,8 +183,18 @@ public override string CommandText
183183 {
184184 Debug . Assert ( WrappingBatch is null ) ;
185185
186- if ( State != CommandState . Idle )
187- ThrowHelper . ThrowInvalidOperationException ( "An open data reader exists for this command." ) ;
186+ switch ( State )
187+ {
188+ case CommandState . Idle :
189+ break ;
190+ case CommandState . Disposed :
191+ ThrowHelper . ThrowObjectDisposedException ( typeof ( NpgsqlCommand ) . FullName ) ;
192+ break ;
193+ case CommandState . InProgress :
194+ default :
195+ ThrowHelper . ThrowInvalidOperationException ( "An open data reader exists for this command." ) ;
196+ break ;
197+ }
188198
189199 _commandText = value ?? string . Empty ;
190200
@@ -252,9 +262,12 @@ protected override DbConnection? DbConnection
252262 if ( InternalConnection == value )
253263 return ;
254264
255- InternalConnection = State == CommandState . Idle
256- ? ( NpgsqlConnection ? ) value
257- : throw new InvalidOperationException ( "An open data reader exists for this command." ) ;
265+ InternalConnection = State switch
266+ {
267+ CommandState . Idle => ( NpgsqlConnection ? ) value ,
268+ CommandState . Disposed => throw new ObjectDisposedException ( typeof ( NpgsqlCommand ) . FullName ) ,
269+ _ => throw new InvalidOperationException ( "An open data reader exists for this command." ) ,
270+ } ;
258271
259272 Transaction = null ;
260273 }
Original file line number Diff line number Diff line change @@ -1694,4 +1694,18 @@ public async Task Completed_transaction_throws([Values] bool commit)
16941694
16951695 Assert. Throws< InvalidOperationException> ( ( ) => cmd. Transaction = tx) ;
16961696 }
1697+
1698+ [ Test, Description( "Writing to properties of a disposed command raises ObjectDisposedException. ") ]
1699+ public async Task Disposed_command_throws_on_assignment( )
1700+ {
1701+ await using var conn = await OpenConnectionAsync( ) ;
1702+ var command = new NpgsqlCommand( "SELECT 1 ") ;
1703+ command. Dispose( ) ;
1704+
1705+ Assert. Throws< ObjectDisposedException> ( ( ) => command. Connection = conn) ;
1706+ Assert. Throws< ObjectDisposedException> ( ( ) => command. CommandText = "SELECT 2 ") ;
1707+
1708+ Assert. That( command. Connection, Is. Null) ;
1709+ Assert. That( command. CommandText, Is. EqualTo( "SELECT 1 ") ) ;
1710+ }
16971711}
You can’t perform that action at this time.
0 commit comments