SearchString问题拉多个查询

时间:2013-10-16 17:29:08

标签: c# asp.net asp.net-mvc-3

我正在尝试获取一个SearchIndex,我已根据某人输入的字符串查询多个数据库表。数字搜索工作正常但我无法弄清楚如何让它搜索其他表格。这是在MVC3中完成的。

 public ActionResult SearchIndex(string searchString)
    {
        var number = from m in db.Numbers
            select m;

        if (!String.IsNullOrEmpty(searchString))
        {
            number = number.Where(s => s.Numbers.Contains(searchString));

        }
        var assignment = from m in db.Numbers
                         select m;
        if (!String.IsNullOrEmpty(searchString))
        {
            assignment = assignment.Where(s => s.Numbers.Contains(searchString));
        }

        return View(number);
    }

也作为侧节点

 select m;

到底是做什么的?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

var mySearchResult = from m in db.MyOtherTables
                          where m.MyField.Contains(searchString)
                          select m;

要了解“m”在这里做什么,你需要了解Linq。有很多很好的教程,你必须谷歌一点。

  1. 这是MSDN: LINQ (Language-Integrated Query)

  2. 以下是Scott Gu Using LINQ with ASP.NET (Part 1)

  3. 的最爱之一
  4. 这是另一个:LINQ to Entities: Basic Concepts and Features
  5. 编辑您的方法可能看起来像这样(只是一个例子):

    public ActionResult SearchIndex(string searchString, string tableName)
    {
        if (!String.IsNullOrEmpty(searchString) && !String.IsNullOrEmpty(tableName))
        {
            switch (tableName.ToLower())
            {
                case "number":
                    var numbers = from m in db.Numbers
                        where m.Number.Contains(searchString)
                        select m;
                    //View "Number" should use strongly typed IEnumerable<Number>
                    return View("Number", numbers);
                case "assignment":
                    var assignments = from m in db.Assignments
                        where m.AssignmentName.Contains(searchString)
                        select m;
                    //View "Assignment" should use strongly typed IEnumerable<Assignment>
                    return View("Assignment", assignments);
                //Add cases for other each tables
                case "mytable":
                    var mytables = from m in db.MyTables
                        where m.MyField.Contains(searchString)
                        select m;
                    //View "MyView" should use strongly typed IEnumerable<MyView>
                    return View("MyView", mytables);
                default:
                    return RedirectToAction("Index");
            }
        }
    
        return RedirectToAction("Index");
    }
    

    希望它有所帮助!