10

I'm trying to get the following LINQ query to work against the database (3.5 SP1):

var labelIds = new List<int> { 1, 2 };
var customersAggregatedTransactionsByType =
    (from transactions in context.TransactionSet
    from customers in context.CustomerSet
        .Where(LinqTools.BuildContainsExpression<Billing.Customer, int>(u => u.LabelId, labelIds))
    from accounts in context.AccountSet
    where customers == accounts.Customer
        && accounts.Id == transactions.Account.Id
        && transactions.DateTime >= fromDate && transactions.DateTime < toDate
    group transactions.Amount
    by new
    {
        UserAccountId = transactions.Account.Id,
        TransactionTypeId = transactions.TransactionTypeId,
        BaseAssetId = accounts.BaseAssetId
    } into customerTransactions
    select customerTransactions).ToList();

Once I add Where(LinqTools.BuildContainsExpression<Billing.Customer, int>(u => u.LabelId, labelIds)) I get the following exception:

System.InvalidOperationException: Internal .NET Framework Data Provider error 1025.

If I remove Where(LinqTools.BuildContainsExpression<Billing.Customer, int>(u => u.LabelId, labelIds)) all's good.

Any help will be appreciated.

Thanks, Nir.

Jan Aagaard
  • 10,940
  • 8
  • 45
  • 80
nirpi
  • 715
  • 1
  • 9
  • 24

1 Answers1

11

Try:

        var labelIds = new List<int> { 1, 2 };
        var exp = LinqTools.BuildContainsExpression<Billing.Customer, int>(u => u.LabelId, labelIds);
        var customersAggregatedTransactionsByType =
             (from transactions in context.TransactionSet
              from customers in context.CustomerSet.Where(exp)
              from accounts in context.AccountSet
              where customers == accounts.Customer
                 && accounts.Id == transactions.Account.Id
                 && transactions.DateTime >= fromDate && transactions.DateTime < toDate
              group transactions.Amount
              by new
              {
                  UserAccountId = transactions.Account.Id,
                  TransactionTypeId = transactions.TransactionTypeId,
                  BaseAssetId = accounts.BaseAssetId
              } into customerTransactions
              select customerTransactions).ToList();

You want the result in the query, not the call to LinqTools.BuildContainsExpression itself.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • 2
    Oh, you genius! I opened a bounty on a [similar question](http://stackoverflow.com/q/11990158/7850) just an hour ago, and only later found your answer. Please go and get yourself a bounty over there. – Shaul Behr Dec 13 '12 at 14:14
  • It sounds obvious, but you are correct, the expression must be built outside of the query itself. – Travis J Sep 05 '17 at 22:40