LIKE在“;其中“;LINQ语句导致错误

本文关键字:错误 语句 其中 LIKE LINQ | 更新日期: 2023-09-27 18:29:21

ProductModel.cs:(类)

public List<Product> GetSearchedProduct (string Name)
{
    try
    {
        using (garagedbEntities db = new garagedbEntities())
        {
            List<Product> products = (from x in db.Products
                                      where x.Name LIKE @txtSearch
                                      select x).ToList();
            return products;
        }
    }
    catch (Exception)
    {
        return null;
    }
}

search.aspx:

 <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master"   AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <asp:Button ID="btnSearch" runat="server" Text="Button" OnClick="btnSearch_Click" />
 <br />
<asp:Panel ID="pnlProducts" runat="server">
    <br />
</asp:Panel>
    <div style="clear:both"></div>

这是我的search.aspx文件。实际上,我想从TextBox中获得product的名称,然后将其传递给检索products的方法。

LIKE在“;其中“;LINQ语句导致错误

在linq中,您应该使用Contains:

List<Product> products = (from x in db.Products
                           where x.Name.Contains(Name)
                           select x).ToList();

编辑:要使用方法,您应该创建一个ProductModel的新实例,然后调用GetSearchedProduct方法并将txtSearch作为参数发送给它

protected void btnSearch_OnClick(object sender, EventArgs e)
{
    ProductModel pr = new ProductModel();
    var result = pr.GetSearchedProduct(txtSearch.Text);
}