Linq to SQL用于搜索查询

时间:2013-12-19 02:24:37

标签: c# sql linq entity-framework

我需要做一个简单的搜索引擎。我找到了这个Microsoft example来帮助我开始。现在,我的问题是将这个函数在linq中编写为sql,这样我就可以在dbcontext应用程序中使用它了。

/// <summary>
/// Search records from database.
/// </summary>
/// <param name="keywords">the list of keywords</param>
/// <returns>all found records</returns>
public List<Article> Search(List<string> keywords)
{
    // Generate a complex Sql command.
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.Append("select * from [Articles] where ");
    foreach (string item in keywords)
    {
        sqlBuilder.AppendFormat("([Title] like '%{0}%' or [Content] like '%{0}%') and ", item);
    }

    // Remove unnecessary string " and " at the end of the command.
    string sql = sqlBuilder.ToString(0, sqlBuilder.Length - 5);

    return QueryList(sql);
}

我在前一个基础上创建了自己的函数:

public List<Record> Search(string[] keywords)
{
    var result = (from c in _context.Tenders
                    where keywords.Contains(c.Title) || keywords.Contains(c.Summary)
                    select new Record()
                    {
                        Id = c.Id,
                        Title = c.Title,
                        Content = c.Summary
                    }).ToList();

    return result;
}

但搜索结果并不相同。如果我在城镇的新合同中搜索合同,我将无法获得结果。我需要写完整的句子才能得到它。你能帮我指出我的linq中缺少什么来实现sql函数吗?

非常感谢!!

2 个答案:

答案 0 :(得分:2)

即将结束,keywords.Contains(c.Title)正在请求与标题完全匹配。你需要做的是反过来翻转它。

public List<Record> Search(string[] keywords)
{
    var result = (from c in _context.Tenders
                  where keywords.Any(w => c.Title.Contains(w)) || keywords.Any(w => c.Summary.Contains(w))
                  select new Record()
                  {
                      Id = c.Id,
                      Title = c.Title,
                      Content = c.Summary
                  }).ToList();

    return result;
}

答案 1 :(得分:0)

您可以将条件用作keywords.Any(w => c.Title.Contains(w)||c.Summary.Contains(w))

将检查标题或摘要包含任何关键字

var result = (from c in _context.Tenders
             where keywords.Any(w => c.Title.Contains(w)||c.Summary.Contains(w))
             select new Record()
             {
                 Id = c.Id,
                 Title = c.Title,
                 Content = c.Summary
             }).ToList();