2013-04-12 107 views
0

我想盡可能地使用LINQ,所以我想把這個弄清楚。我能夠使用DataContext ExecuteQuery方法獲取用戶選擇的服務器/數據庫中的表的列表,但不使用Mapping.GetTables()枚舉器。Linq DataContext.Mapping.GetTables()什麼也沒有返回

以下是我已經(被BackgroundWorker.RunWorkerAsync(參數)調用):

//Build the connection string (args contains the Server and database names) 
Dictionary<string, string> args = (Dictionary<string, string>)e.Argument; 
string ConnectString = "Data Source=" + args["SqlServerHolder"] + ";Integrated Security=True;Initial Catalog=" + args["SqlServerDatabaseHolder"]; 

//Get the connection and pull the list 
using (SqlConnection con = new SqlConnection(ConnectString)) 
{ 
    // Open connection 
    con.Open(); 

    //create a linq connection and get the list of database names 
    DataContext dc = new DataContext(con); 

    //THIS WORKS 
    e.Result = new ObservableCollection<string>(dc.ExecuteQuery<string>("SELECT [name] FROM sysobjects WHERE xtype='U'").AsEnumerable()); 

    //THIS COMES BACK EMPTY (tables) 
    IEnumerable<string> tables = (from mt in dc.Mapping.GetTables() select mt.TableName); 
    e.Result = new ObservableCollection<string>(tables); 
} 

運行硬編碼的查詢工作,但我寧願使用的getTables()方法來避免這種情況。我能想到的唯一的事情就是數據庫就像這樣連接起來,我不知何故必須填充映射?

感謝 厄尼

回答

0

LINQ到SQL需要一些代碼來處理ORM的功能 - 它的工作原理與強類型的類。

現在你選擇一個隨機數據庫,沒有可用的映射,因此沒有結果。換句話說,隨機數據庫沒有DBML ..

其他語句只是普通的SQL,因此它可以在任何隨機數據庫中工作,但它確實返回任何強類型的數據。

+0

謝謝,這是有道理的。所以我想在這種情況下最好/唯一的方法是使用硬編碼查詢字符串? DataContent對象是否真的比傳統的ADO對象提供任何好處? – Ernie

+0

我認爲你的情況是好處很少。 – Pleun