LIKE在“where”LINQ语句导致错误

时间:2016-01-07 19:29:09

标签: c# asp.net entity-framework linq

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文件。实际上我希望从product获取TextBox的名称,然后将其传递给检索products的方法。

1 个答案:

答案 0 :(得分:5)

在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);
}