2014-10-02 83 views
1

我一直在苦苦掙扎着這段代碼,我是新手,所以請耐心等待。Linq搜索查詢多個表

以下代碼非常適合在名爲Blog的表中搜索。不過我有3個表,它看起來像這樣:

--[FE] 
----- [Blog] 
----- [Bolted_steltanks] 
----- [Mixers] 
----- [Windpower] 

我想我的代碼搜索所有4桌,現在只搜索1臺。下面這裏有我的部分代碼:

var q = from p in dbBlog.Blog.ToList() 

       //join w in dbAlbum.Windpower on p.Description equals w.Description 

       where 
        Data.Any(x => p.Description.IndexOf(x) >= 0) || 
        Data.Any(x => p.Date.IndexOf(x) >= 0) 
       orderby p.id descending 
       select p; 
return View("Found", q.ToList()); 

另一個小小的問題是,收到的結果查看。我不確定如何創建模型,其中一個表適用於此代碼:

@model IEnumerable<FE.Blog> 

任何幫助都非常感謝。

回答

1

你可以像下面一樣使用linq來連接多個表。

from t1 in Table1 
join t2 in Table2 on t2.Id equals t1.Id //OR matching field 
join t3 in Table3 on t3.Id equals t1.t3Id //OR matching field 
where t1.ConditionColumn == value // OR all your where clause to come here 
select new { col1 = t1.col1, col2 = t1.col2, col3 = t1.col3, col4 = t2.col1, col5 = t3.col1 }; //OR all your select to come here 

我不認爲這是需要有@model IEnumerable<FE.Blog>。 /這樣的多表聲明

+0

如果我沒有任何@model ...在視圖中,我無法檢索任何模型項目,所有東西都會崩潰。我使用過你的代碼,沒有語法錯誤,我也沒有得到任何結果,因爲視圖也許? – Varg 2014-10-02 15:54:04

+0

我寫了一個包含所有必需屬性的新模型。 @CodeMad,感謝您的回答,我從這幾行中學到了很多東西。 – Varg 2014-10-06 21:00:56