Toad Toad - 11 months ago 70
C# Question

what is the easiest way to have multiple db connections when using linq

Optimally I would like linq to use X database connections instead of 1 to speed things up.

The only way now is to open X connections, and create X databasecontexts, and associate them.
It would be easier if somehow I could tell linq to use X connections.

Is this possible? Or is there another way to speed up database queries?


edit: changed the title since it was misleading (according to one of the answerers, and I agree)

Answer Source

I think the title is misleading. Connection Pooling: You don't need to do that. Linq2SQL uses an ADO.NET SqlConnection under the hood which is connection pooled by default.

What you are trying to accomplish seems to me like trying to query the database in parallel. This can only beneficial if you are trying to execute different queries or a query that can be very well parallelized. Such a query also should not heavily rely on locks/transaction. Slow queries generally tend not to be of that kind.

Loading the top 50% of the same query with one connection and the bottom 50% with another won't bring you any benefits, the Database Server is the bottleneck there.

There are a lot of other reasons why LinqToSql SQL queries perform bad. One of them is known as the Select N+1 problem. Ayende has a great post about fighting it in NHibernate, equivalent principles apply in L2S.

If all of the above does not help you, you might want to take a look at SQL Server MARS that allows you to query a database in parallel on one connection.