【问题标题】:Why does ObjectDataSource require an optional parameter of a function?为什么 ObjectDataSource 需要函数的可选参数?
【发布时间】:2016-07-27 04:24:10
【问题描述】:

这个ObjectDataSource在连接到以下函数时会返回错误:

<asp:ObjectDataSource ID="odsActiveProductTypes" runat="server" SelectMethod="GetProductTypes" TypeName="MyRepo">

带可选参数的函数:

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

这是错误:

ObjectDataSource 'odsActiveProductTypes' 找不到非泛型 没有参数的方法“GetProductTypes”。

我意识到我可以通过向ObjectDataSource 添加参数来使代码工作,或者我可以重载函数,但这违背了可选参数的目的。

【问题讨论】:

    标签: .net optional-parameters objectdatasource


    【解决方案1】:

    这可能是 .NET 中的一个错误。

    当数据源试图找到要绑定的方法时,它正在运行this code,其中part of it 正在检查:

    if (methodParametersCount != allParameterCount) {
        continue;
    }
    

    methodParametersCount 是您方法中的参数计数,在您的情况下为 1,尽管它是可选的。由于你没有给它任何参数传递给方法,allParameterCount 为 0,所以它继续寻找更多的方法。

    没有找到任何,它ends up 检查它是否匹配一个方法。如果不是,它会再次检查您提供了多少参数,如果为 0(如您的情况),则抛出您看到的异常:

    if (allParameterCount == 0) {
        throw new InvalidOperationException(SR.GetString(SR.ObjectDataSourceView_MethodNotFoundNoParams, _owner.ID, methodName));
    }
    

    正如你所说,简单的解决方法是创建一个不带参数的重载。

    【讨论】:

    • 我特别感谢您深入了解并用引用的来源支持您的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2011-02-25
    • 2019-03-11
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多