LINQ查询多个数据库c#

时间:2013-07-04 15:12:52

标签: c# database linq

我没有找到任何使用LINQ查询多个数据库的好材料。我一直在使用连接字符串在数据库之间进行更改并为用户显示数据,现在我想实现一个查询所有数据库并返回列表而不是事先选择数据库的搜索功能。

这是我到目前为止所抛出的一切。从一个数据库返回一个列表,这显然不是我想要的。

 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 个答案:

答案 0 :(得分:1)

问题是你在foreach循环中不断重新分配customers变量:

    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();