Expression tree for count ()> 1

I am using EF 6.1 and I would like to query my objects using the following SQL

SELECT field, count(*) 
FROM entity
GROUP BY field
HAVING COUNT(*) > 1

Here both fieldand entityare variable. If both of them were known at compile time, I could useContext.Set<Entity>().GroupBy(e => e.Field).Where(f => f.Count() > 1).Select(f => f.Key)

EDIT Forgot to mention that it fieldalways has a type string.

I think you can use the expression tree, but I'm not very familiar with this, and the learning curve is a little steep.

public Func<TSource, what the return type?> CountMultiple<TSource>(string field)
        {
            var parameter = Expression.Parameter(typeof(TSource), "p");
            var property = Expression.Property(parameter, field);
.
Some more Expression magic goes here                
.

            return Expression.Lambda<Func<TSource, the return type>>(?, ?).Compile();
        }

Can someone point me in the right direction?

EDIT

To clarify; I'm looking for something like this (below will check the fieldtype entity TSourcefor null)

public Func<TSource, bool> IsNull<TSource>(string field)
        {
            var parameter = Expression.Parameter(typeof(TSource), "p");
            var property = Expression.Property(parameter, field);
            return Expression.Lambda<Func<TSource, bool>>(
                Expression.Equal(property, Expression.Constant(null, property.Type)), new[] { parameter }).Compile();
        }

Then I can use it as follows

context.Set<TEntity>()
                    .Where(e => !e.AMT_ValidationStatus.Equals(ValidationStatus.FAILED.ToString()))
                    .Where(IsNull<TEntity>(f.Name))
+4
1

,

public static IQueryable<IGrouping<string, TSource>> Grouper<TSource>(IQueryable<TSource> source, string field)
        {
            var parameter = Expression.Parameter(typeof(TSource), "x");
            var property = Expression.Property(parameter, field);
            var grouper = Expression.Lambda<Func<TSource, string>>(property, parameter);

            return source.GroupBy(grouper);
        }

(f.Name - TEntity)

Grouper(context.Set<TEntity>(), f.Name)
                                .Where(field => field.Count() > 1)
                                .Select(s => new { Key = s.Key, Count = s.ToList().Count })
0

Source: https://habr.com/ru/post/1648018/


All Articles