根据不同的列或字段值过滤结果

时间:2011-11-09 20:23:08

标签: sql asp.net-mvc-3 entity-framework

我有一个针对MS SQL 2008数据库运行的MVC 3应用程序,其中包含一个名为Documents的表。文档按数据库中的段落细分。 Documents表有一个DocText列,其中包含每个段落的文本,DocTitle列包含文档标题。我的MVC 3应用程序具有搜索功能,可以在DocText列或DocTitle列中搜索单词或短语。一切正常,但如果某个特定文档的搜索词出现在多个段落中,我的列表会返回该文档的多个实例。例如,如果用户搜索单词“预算”,并且其中一个文档在四个不同的段落中都有单词“预算”,则我返回的列表会将该文档列出四次。

我想要实现的是列出每个包含搜索词的文档。我只想按标题列出文档一次,无论搜索字出现在该文档中的次数如何。唯一真正唯一的列是RecordID列,即主键。

我的控制器:

    public class SearchController : Controller
{

    private GUICEEntities4 db = new GUICEEntities4();

    //
    // GET: /Search/

    public ActionResult Index(string Keyword)
    {
         #region Keyword Search
        if (!String.IsNullOrEmpty(Keyword)) {
            var SearchDoc = db.Documents.Where(r => r.DocText.ToUpper().Contains(Keyword.ToUpper()) || r.Title.ToUpper().Contains(Keyword.ToUpper()) || r.DocNum.ToUpper().Contains(Keyword.ToUpper()));

            ViewBag.CurrentKeyword = String.IsNullOrEmpty(Keyword) ? "" : Keyword;

            return View(SearchDoc.ToList());
        }
            else{
             return View();
            }
              #endregion
    }

 }

我的观点包含以下内容:

@foreach (var item in Model) {

    <tr>
        <td>
            <strong>AFI @Html.DisplayFor(modelItem => item.DocNum): @Html.DisplayFor(modelItem => item.Title)</strong>
            <br />
            @Html.DisplayFor(modelItem => item.DocSummary)
            <br />
            <span class="complianceitems">Number of compliance items:</span> (TBD)
        </td>

        <td>
            <a href="/Documents/Index/@(Html.DisplayFor(modelItem => item.DocNum))">Checklist
                Generator</a><br />
            <a href="/UploadedDocs/@Html.DisplayFor(modelItem => item.DocFileName)" target="_blank">
                Download PDF</a>
        </td>

关于如何实现目标的任何建议?

ADDED:每个文档都可以通过DocNum列进行标识,该列具有该特定文档的唯一文档编号。我试图遍历List以取出每个unqiue DocNum,然后尝试让DocNum不再出现在循环中......但我没有成功。

以下SQL语句为我提供了我需要的结果。该陈述假设搜索词是“预算”。我不知道如何使用EF获得相同的结果。有什么建议吗?

SELECT DISTINCT DocNum, Title FROM Documents
WHERE
DocText LIKE '%budget%'
OR
Documents.Title LIKE '%budget%'
OR
DocNum LIKE '%budget%'

1 个答案:

答案 0 :(得分:0)

此处的问题出在您的EF查询中,而不是与MVC相关的任何内容。我已经有一段时间积极使用EF,但最简单的方法可能是首先返回RecordIds。

var recordIds= db.Documents
                  .Where(r => 
                         r.DocText.ToUpper().Contains(Keyword.ToUpper()) ||
                         r.Title.ToUpper().Contains(Keyword.ToUpper()) ||
                         r.DocNum.ToUpper().Contains(Keyword.ToUpper()))
                  .Select(d => d.RecordId)
                  .Distinct();

由于您的问题中没有足够的信息,我不确定从那时起您将对每条记录做些什么。但这应该有所帮助。

更新

var foundDocs = new List<YourType>();
recordIds.ToList().ForEach(r => foundDocs.Add(db.TblDocLists.Single(l => l.TheDocNum == r)));
//I must point out that I'm not familiar with the latest versions of EF so this might be overkill.