Friday, January 22, 2016

MultipleActiveResultSets–what is it and should I use it?

On a project I had to review, I saw that one of the developers had enabled MultipleActiveResultSets(MARS) in the connection string. 

"Data Source=MSSQL1;Initial Catalog=AdventureWorks;Integrated Security=SSPI;MultipleActiveResultSets=True";

When I asked if he was aware that it was enabled and asked the reasoning behind it, the answer was a blank stare:

image

He just copied the connectionstring over from another project but had no idea why this setting was there.

MARS was introduced in SQL Server 2005 and enable the possibility to maintain multiple active statements in one connection. This enables the following possibilities:

  • Applications can have multiple default result sets open and can interleave reading from them.

  • Applications can execute other statements (for example, INSERT, UPDATE, DELETE, and stored procedure calls) while default result sets are open.

I see it most of the time in combination with Entity Framework when someone is using LINQ to iterate over a set of results and while iterating lazy loads related items. Most of the time, this is not a good idea as it indicates a N+1 problem that could be solved by materializing the parent collection or eager loading the related items.

More information:

1 comment:

Anonymous said...

Returning multiple result sets is useful if you're using plain ADO.NET or Dapper and want to get multiple result sets. It's also great for this: https://github.com/loresoft/EntityFramework.Extended/wiki/Future-Queries