Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use FirstOrDefault on SqlParameterCollection

Tags:

c#

linq

There is a method that examines an SqlParameterCollection for a ReturnValue parameter and if present checks that value for a constraint violation.

      public static void VerifyUniqueness(this ISqlServerProvider provider, 
OperationType operationType, SqlParameterCollection cp)

Within this method I thought it was enough to first check:

if (cp["@ReturnValue"]==null){return;}

but that throws an exception if "@ReturnValue" == null so then I thought I'd use Linq:

cp.FirstOrDefault(p => p.ParameterName == "@ReturnValue");

but that wont even compile.

'System.Data.SqlClient.SqlParameterCollection' does not contain a definition for 'FirstOrDefault' and no extension method 'FirstOrDefault' accepting a first argument of type 'System.Data.SqlClient.SqlParameterCollection' could be found (are you missing a using directive or an assembly reference?)

System.Linq is referenced so not sure what's going on.

like image 297
rism Avatar asked Oct 16 '25 01:10

rism


1 Answers

The reason you can't use FirstOrDefault is that SqlParameterCollection does not implement IEnumerable<SqlParameter> (on which the LINQ expressions are defined).

The intended method of checking for a parameter is to use Contains

if (cp.Contains("@ReturnValue"))

If you really want to use LINQ operators, you can use Cast:

cp.Cast<SqlParameter>()
  .FirstOrDefault(p => p.ParameterName == "@ReturnValue")
like image 133
Richard Szalay Avatar answered Oct 18 '25 15:10

Richard Szalay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!