0

I currently get 2 aggregate function results this way:

var fooCount = ctx.Foo.Count();
var barCount = ctx.Bar.Count();

This produces 2 different SQL queries. I am looking for a way to combine these into one query.

In plain SQL I can combine these two queries this way:

SELECT 
  (SELECT COUNT(*) FROM Foo) AS FooCount,
  (SELECT COUNT(*) FROM Bar) AS BarCount

How can we do this using Entity Framework? All I have found was for multiple aggregate function in the same table. But in my case it are different tables.

I tried something like this with no success:

var query = from together in (new
{
    FooCount = db.Foo.Count(),
    BarCount = db.Bar.Count()
}) select together; //<-- visual studio let me not write "select together;"
3
  • You are creating a Anonymous types, not a IEnumerable, why not new int[] {ctx.Foo.Count(), ctx.Bar.Count()} Commented May 5, 2016 at 14:33
  • I am trying to execute this in one query. @ArturoMenchaca Commented May 5, 2016 at 14:34
  • @ArturoMenchaca Each call to Count is going to create a separate SQL call and the OP wants to combine them into one. Commented May 5, 2016 at 14:34

1 Answer 1

3

I think what you want is something like this. Basically grouping by a constant allows you to do the count aggregation as an IQueryable<int> and then you can cross join them. But I don't know that it's worth it. Basically you're trading readability for presumably some increase in performance.

var counts = (from fc in (
                 from f in ctx.Foo
                 group f by 1 into fgrp
                 select fgrp.Count())
             from bc in (
                 from b in ctx.Bar
                 group b by 1 into bgrp
                 select bgrp.Count())
             select new { FooCount = fc, BarCount = bc }).Single();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It seems like it is generating a cross join, but I assume this is no problem, because it is calculating Sum before?
Yeah the cross join is going to be against two sets that each have one row. I would expect the SQL from this to roughly have the same query plan as your SQL, but don't hold me to that. It's best to test this against doing the counts separately to determine which is faster, assuming that's what your goal is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.