I have multiple databases with the same schema/context and I want to query them all. I want to execute the same query on each database. I cannot use Linked Servers in SQL because the databases are created/deleted on the fly. Is there some way I can create some extension method for the context, so the query will execute on all of them? (sequentially or parallel)
I have already done this for one table but I want something that can work for all tables, so I don't have to write the same code for each table.
ConcurrentBag<FindConstructionSearchResult> results = new();
Parallel.ForEach(connStrings, new() { MaxDegreeOfParallelism = 16 }, dbConnectionInfo =>
{
DB_DataContext dctx = DbHelper.Get_DataDBContext(dbConnectionInfo.DbName, dbInstance);
List<FindConstructionSearchResult> sstavby = dctx.SStavby.Where(x => x.Nazev.Contains(request.ConstructionName) || x.Znacka.Contains(request.ConstructionName)).Select(x => new FindConstructionSearchResult()
{
ConstructionMark = x.Znacka,
ConstructionName = x.Nazev,
Database = dbConnectionInfo.DbName
}).ToList();
foreach (var item in sstavby)
{
results.Add(item);
}
});
this is pretty fast, but I don't think it is elegant.
2条答案
按热度按时间osh3o9ms1#
You've got the basic implementation right, just need to wrap it up in a tidy method. EG
im9ewurl2#
The final implementation I used is following:
"DB_DataContext" is the actual DbContext I am using. The method "Get_DataDBContext" returns requested context for given Db Name and Sql Instance. I modified the return Type so I can see from which database the result is.