在linq语句中添加自定义函数

时间:2010-09-08 07:00:00

标签: c# linq-to-sql

嗨伙计们我想在关键字字段中搜索,例如集合中的搜索键。我的关键是“Wing”关键词是“Wing Dress Others”的空格我应该写什么呢?
错误:方法'布尔比较(System.String,System.String)'没有支持的SQL转换。

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString.HasKeys())
    {
        DbDataContext db = new DbDataContext();
        var Query = from n in db.Products
                    where Compare(n.Keywords, Request.QueryString["key"])
                    select n;
        DataList1.DataSource = Query;
        DataList1.DataBind();
    }
}

bool Compare(string keywords,string key)
{
    string[] items = keywords.Split(' ');
    foreach (string item in items)
        if (item.Equals(key)) return true;
    return false;
}

2 个答案:

答案 0 :(得分:5)

类似于que / ans:Custom Method in LINQ to SQL query

查看完整文章:What is and what isn't possible with linq

以下是不可能的

// function used in filter
static bool MyFunc(Nwind.Product p)
{
  return p.ProductName.StartsWith("B");
}
// query that uses MyFunc
var q = 
  from p in db.Products
  where MyPriceFunc(p.UnitPrice) > 30m
  select p

它编译时没有错误,但是当你执行它时,LINQ to SQL会抛出一个异常,说:“静态方法System.Boolean MyTest(LINQTest.Nwind.Product)没有支持的SQL转换。”

当您尝试从q获取结果时(例如使用foreach语句),实际上会抛出异常,因为只有在需要结果并且查询必须是的时候,LINQ to SQL才会尝试将表达式树转换为T-SQL执行。

要修复该示例,您只需将检查产品名称是否以“B”开头的代码复制到查询的where子句中,它就可以正常工作。

答案 1 :(得分:2)

在这种情况下,您可以使用Compare来检查字符串是否在字符串中,而不是自制Contains。这适用于LINQ

示例:

    var Query = from n in db.Products
                where n.Keywords.Contains(Request.QueryString["key"])
                select n;

也包含数组的工作。