2013-10-16 66 views
1

我想獲得一個SearchIndex我寫了基於某人輸入字符串查詢多個數據庫表。數字搜索工作正常,但我不知道如何讓它搜索其他表以及。這是在MVC3中完成的。SearchString問題拉多個查詢

​​

另外,作爲一個側節點

select m; 

究竟是什麼呢?

回答

1

你可以這樣做:

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

要了解什麼是 「M」 是在這裏做,你需要知道的LINQ。有很多好的教程,你必須谷歌一點。

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

  2. 下面是從斯科特谷Using LINQ with ASP.NET (Part 1)

  3. 我最喜歡的之一,這裏的另一個問題:LINQ to Entities: Basic Concepts and Features

編輯你的方法看起來像這樣(只是一個例子):

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"); 
} 

希望它能幫助!