【发布时间】:2014-01-03 04:15:40
【问题描述】:
我需要做一个简单的搜索引擎。我找到了这个Microsoft example 来帮助我开始。现在,我的问题是在 linq to 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;
}
但是搜索结果不一样。如果我在 New contract in town 中搜索 Contract,我不会得到结果。我需要写完整的句子才能得到它。你能帮我指出我的 linq to sql 函数中缺少什么来实现这一点吗?
非常感谢!!
【问题讨论】:
标签: c# sql linq entity-framework