Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET - Advanced Where-Clause in LinqDataSource

I have two tables:

  1. Orders
  2. OrderProducts - An order can have 1 to many orderProducts records associated with it.

What I am trying to do (unsuccessfully) is to implement a GridView search using a LinqDataSource wherein the search returns Order results where any of the OrderProduct.Manufacturer columns contain a search query.

I was hoping the following would work, however it seems lambda expressions do not work within a Where clause of a LinqDataSource (in VB):

    <asp:LinqDataSource ID="dsOrders" runat="server" ContextTypeName="myDataContext" TableName="orders"
        Where="orderProducts.Any(Function(op) op.Manufacturer.Contains(@searchTerm))">
        <WhereParameters>
            <asp:ControlParameter Name="searchTerm" ControlID="txtSearchTerm" DefaultValue="" />
        </WhereParameters>
    </asp:LinqDataSource>

In C# it would look like:

   <asp:LinqDataSource ID="dsOrders" runat="server" ContextTypeName="myDataContext" TableName="orders"
        Where="orderProducts.Any(op => op.Manufacturer.Contains(@searchTerm))">
        <WhereParameters>
            <asp:ControlParameter Name="searchTerm" ControlID="txtSearchTerm" DefaultValue="" />
        </WhereParameters>
    </asp:LinqDataSource>

The error I am getting is:

No property or field 'op' exists in type 'orderProduct'

Any clues as to how to get this working within the LinqDataSource definition, or will I have to handle and set up a custom OnSelecting event?

like image 684
Keith Avatar asked Dec 28 '22 06:12

Keith


1 Answers

I figured it out. I didn't realize this until now, but apparently LinqDataSource select/where/etc clauses use a different syntax than standard Linq. All I needed to do was the below (among other cleanup). Hope this helps someone else in the future:

    <asp:LinqDataSource ID="dsOrders" runat="server" ContextTypeName="myDataContext" TableName="orders"
        Where='@searchTerm = "" OR Convert.ToString(orderID) = @searchTerm OR orderProducts.Any(Manufacturer.Contains(@searchTerm))'>
        <WhereParameters>
            <asp:ControlParameter Name="searchTerm" ControlID="txtSearchTerm" DefaultValue="" ConvertEmptyStringToNull="false" />
        </WhereParameters>
    </asp:LinqDataSource>
like image 189
Keith Avatar answered Jan 10 '23 18:01

Keith