PetaPoco icon indicating copy to clipboard operation
PetaPoco copied to clipboard

Mixing Indexed and Named Arguments throw a NullReferenceException

Open Curlack opened this issue 4 years ago • 2 comments
trafficstars

select 1 where @0 = @Condition @0 = null @Condition = 1

I'm using db.FetchAsync(cancellationToken, sql, args) method

For the second parameter, PetaPoco will iterate through all arguments to find an object with the name "Condition". Problem is that @0 is null and null.GetType() throws the exception.

Suggestions: Using the null-condition operator e.g. o?.GetType() of filter the null values before iterating e.g. foreach (var o in args_src.Where(o => o != null))

The issue is in the ParametersHelper line 57 under the comment "Look for a property on one of the argument with this name"

Curlack avatar Jul 28 '21 11:07 Curlack

Note that the same exception can be thrown, legitimately, even without indexed arguments.

ObjectWithConditionProperty myObj = null;
db.Fetch<object>("select 1 where Foo = @condition", myObj);

If we change the loop so that we ignore any args which are null, the above code would throw a different exception. Which exception better describes what's going on? The object I passed in does have a condition property, but the instance is null.

asherber avatar Jul 29 '21 05:07 asherber

I see what you mean, but the way I'm passing named arguments is new { name = value } i.e. always using an instance. Maybe ignoring nulls using the null-condition operator and modifying the exception to include both causes e.g. Parameter '{0}' specified but couldn't be found. Either it's missing, misspelled or has a null reference.\r\n{1} The code shouldn't fail the moment it can't determine the type. It should complete the args scan and only fail based when !found. I think it's fair to say that named arguments must always be object wrappers of indexed arguments i.e. always have an instance with at least one property of some supported type. From what I can see, the supported type are only types that can resolve their value to string and enumerables of those types.

Curlack avatar Jul 29 '21 06:07 Curlack