Note that there are some explanatory texts on larger screens.

plurals
  1. POAggregating multiple queries into one with EF like this?
    text
    copied!<p>I am using EF 4.0 POCO in my application. <strong>Are there any downsides to retrieving information like this?</strong></p> <p>Given a <code>customerId</code> and a <code>productId</code>, I would like to apply some business rules that require me to fetch lots teeny pieces of information from the database requiring multiple queries. Instead, I could write one query like so:</p> <pre><code>var customerId = 1; var productId = 1; var aggregateQuery = from entry in Customers.Take(0).DefaultIfEmpty() select new { numberOfOrders = SalesOrderHeaders.Where (header =&gt; header.CustomerID == customerId).Count(), canSellProduct = Products.Where(product =&gt; product.ProductID == productId &amp;&amp; product.SellEndDate &gt; DateTime.Now).Count () &gt; 0 //more infromation of this sort, required to enforce business rules }; var informationPacket = aggregateQuery.First(); </code></pre> <p>The <code>Customers.Take(0).DefaultIfEmpty()</code> just gives a way to start the query and <code>Customers</code>, <code>SalesOrderHeaders</code> and <code>Products</code> are EF ObjectQuery instances from the context (This example if from LinqPad). This results in the following SQL:</p> <pre><code>-- Region Parameters DECLARE @p0 Int = 1 DECLARE @p1 Int = 1 DECLARE @p2 DateTime = '2012-04-04 21:02:20.798' DECLARE @p3 Int = 0 -- EndRegion SELECT TOP (1) [t6].[value] AS [numberOfOrders], [t6].[value2] AS [canSellProduct] FROM ( SELECT ( SELECT COUNT(*) FROM [Sales].[SalesOrderHeader] AS [t3] WHERE [t3].[CustomerID] = @p0 ) AS [value], (CASE WHEN (( SELECT COUNT(*) FROM [Production].[Product] AS [t5] WHERE ([t5].[ProductID] = @p1) AND ([t5].[SellEndDate] &gt; @p2) )) &gt; @p3 THEN 1 WHEN NOT ((( SELECT COUNT(*) FROM [Production].[Product] AS [t5] WHERE ([t5].[ProductID] = @p1) AND ([t5].[SellEndDate] &gt; @p2) )) &gt; @p3) THEN 0 ELSE NULL END) AS [value2] FROM ( SELECT NULL AS [EMPTY] ) AS [t0] OUTER APPLY ( SELECT TOP (0) NULL AS [EMPTY] FROM [Sales].[Customer] AS [t1] ) AS [t2] ) AS [t6] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload