2013-07-04 107 views
3

我還沒有發現任何使用LINQ查詢多個數據庫的好材料。我一直在使用連接字符串來改變數據庫和顯示用戶數據,現在我想實現一個查詢所有數據庫的查詢函數,並返回一個列表,而不是事先選擇數據庫。LINQ查詢多個數據庫c#

這就是我到目前爲止扔到一起。它從一個數據庫返回一個列表,這顯然不是我想要的。

public ActionResult getCustomers(string cust) 
    { 
     List<trakman_Entities> teInstances = new List<trakman_Entities>(); 
     IEnumerable<customer> customers = null; 


     for (var i = 1; i < ConfigurationManager.ConnectionStrings.Count; i++) 
     { 

      if (ConfigurationManager.ConnectionStrings[i].ConnectionString.ToLower().Contains("metadata")) 
      { 
       string con = ConfigurationManager.ConnectionStrings[i].ConnectionString; 
       teInstances.Add(new trakman_Entities(con)); 

      } 

     } 

     foreach (trakman_Entities entitiy in teInstances) 
     { 
      customers = entitiy.customers.Where(c => c.code.StartsWith(cust)); 

     } 

     foreach(customer c in customers) 
     { 
      Response.Write(c.code); 
      Response.Write(c.name); 

     } 

     Response.End(); 
     return View(customers); 
    } 

回答

1

的問題是,你把重新分配客戶的變量在您的foreach循環:除了

foreach (trakman_Entities entitiy in teInstances) 
    { 
     // overwrites on each iteration! 
     customers = entitiy.customers.Where(c => c.code.StartsWith(cust)); 

    } 

,考慮:

var customers = teInstances.SelectMany(e => e.customers.Where(c => c.code.StartsWith(cust))) 
    .ToList(); 

或者,使用單一的做做這件事LINQ查詢:

// start with the list of connection string settings cast to IEnumerable<T> 
var customers = ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>() 
    // filter to the relevant connection strings 
    .Where(s => s.ConnectionString.ToLower().Contains("metadata")) 
    .SelectMany(s => { 
     // for each connection string, select a data context   
     using(var context = new trakman_entities(s.ConnectionString)) { 
      // for each context, select all relevant customers 
      return context.customers.Where(c => c.code.StartsWith(cust)).ToArray(); 
     } // and dispose of the context when we're done with it 
    }) 
    .ToList(); 
+0

我知道l ol,我有點卡住實現一個包含客戶列表的列表。 –

+0

@Simon你試過我的建議嗎? – ChaseMedallion

+0

@ChaseMedallion better'customers.Add(...)'where'customers' is'List' –