Search code examples
linq-to-sqlaggregate

Return multiple aggregate columns in LINQ


I would like to translate the following SQL into LINQ:

SELECT
    (Select count(BidID)) as TotalBidNum,
    (Select sum(Amount)) as TotalBidVal
FROM Bids

I've tried this:

from b in _dataContext.Bids
select new { TotalBidVal = b.Sum(p => p.Amount), TotalBidNum = b.Count(p => p.BidId) }

but get an error "Bids does not contain a definition for "Sum" and no extension method "Sum" accepting a first argument of type "Bids" could be found.

How can I do this in LINQ?

Thanks

CONCLUDING:

The final answer was:

var ctx = _dataContext.Bids;

var itemsBid = (from b in _dataContext.Bids
               select new { TotalBidVal = ctx.Sum(p => p.Amount), TotalBidNum = ctx.Count() }).First();

Solution

  • You could try this out. The variable b is an entity (for every iteration) while ctx is an entityset which has the extension methods you need.

    var ctx = _dataContext.Bids;
    
    var result = ctx
        .Select( x => new
        {
            TotalBidVal = ctx.Sum  ( p => p.Amount ),
            TotalBidNum = ctx.Count( p => p.BidId  )
        } )
        .First();