Reputation: 19446
This ObjectDataSource
will return an error when connecting to the following function:
<asp:ObjectDataSource ID="odsActiveProductTypes" runat="server" SelectMethod="GetProductTypes" TypeName="MyRepo">
Function with optional parameter:
Public Function GetProductTypes(Optional ByVal activeOnly As Boolean = True) As IQueryable(Of ProductType)
If activeOnly Then
Return MyContext.ProductTypes.Where(Function(pt) pt.Active = True)
Else
Return MyContext.ProductTypes
End If
End Function
Here's the error:
ObjectDataSource 'odsActiveProductTypes' could not find a non-generic method 'GetProductTypes' that has no parameters.
I realize I can make the code work by adding a parameter to the ObjectDataSource
or I could overload the function but that defeats the purpose of an optional parameter.
Upvotes: 2
Views: 429
Reputation: 32212
It's arguably a bug in .NET.
When the data source is attempting to find the method to bind to, it's running this code, where part of it is checking:
if (methodParametersCount != allParameterCount) {
continue;
}
Where methodParametersCount
is the count of parameters from your method, which in your case will be 1, albeit optional. Since you haven't given it any parameters to pass to the method, allParameterCount
is 0, so it continues looking for more methods.
Having not found any, it ends up checking to see if it's matched a method. If not, it again checks to see how many arguments you supplied, and if 0 (as in your case), throws the exception you're seeing:
if (allParameterCount == 0) {
throw new InvalidOperationException(SR.GetString(SR.ObjectDataSourceView_MethodNotFoundNoParams, _owner.ID, methodName));
}
As you say, the simple fix is to create an overload with no parameters.
Upvotes: 3