Theo Koekemoer
Theo Koekemoer

Reputation: 228

Dynamic Linq Group by Join and Count

Good day. Need some help with Dynamic Linq Query. I have the following SQL.

Select t.CustomerKey , Count(1)
    from dbo.Products p
    inner join dbo.Transactions t on t.ProductKey = p.ProductKey
    Where p.CategoryLevel3 = 'xxx'
    group by t.CustomerKey
    having count(1) > 2

I am using Entity Framework. The linq query I have that gives me the same result is.

var result2 = entities.Products.Join(entities.Transactions, p => p.ProductKey, t => t.ProductKey, (p, t) => new { p, t })
                               .Where(z => z.p.CategoryLevel3 == "xxx")
                               .GroupBy(c => new { c.t.CustomerKey })
                               .Select(x => new { x.Key.CustomerKey, count = x.Count() })
                               .Where(y => y.count > 2);

So far I have the following Dynamic Linq

var result2 = entities.Products.Join(entities.Transactions, p => p.ProductKey, t => t.ProductKey, (p, t) => new { p, t })
                               .Where("z => z.p." + filterCondition)
                               .GroupBy("c => new { c.t." + groupByField + "}")
                               .Select("x => new (x.Key as CustomerKey, x." + selectfunction + "() as count)")
                               .Where("y => y.count" + groupByFilterComparisonOperator + groupByFilterInputValue);

I get a Syntax Error on the Select Line.

filterCondition = "CategoryLevel3 == "xxx""

groupByField ="CustomerKey"

selectfunction ="Count"

groupByFilterComparisonOperator =">"

groupByFilterInputValue = "2"

Upvotes: 0

Views: 424

Answers (1)

Theo Koekemoer
Theo Koekemoer

Reputation: 228

I found the answer

var result2 = entities.Products.Join(entities.Transactions, p => p.ProductKey, t => t.ProductKey, (p, t) => new { p, t })
                               .Where("z => z.p." + filterCondition)
                               .GroupBy("c => new { c.t." + groupByField + "}")
                               .Select("new (Key , " + selectfunction + "() as count)")
                               .Where("count" + groupByFilterComparisonOperator + groupByFilterInputValue);

Upvotes: 1

Related Questions