I'm using EF 6.1 and I would like to query my entities using the following SQL
SELECT field, count(*)
FROM entity
GROUP BY field
HAVING COUNT(*) > 1
Here both field
and entity
are variable. If both were known at compile time I could use Context.Set<Entity>().GroupBy(e => e.Field).Where(f => f.Count() > 1).Select(f => f.Key)
EDIT
Forgot to mention that field
is always of type string.
I think it is possible using an expression tree, but I'm not very familiar with that and the learning curve is a bit steep.
public Func<TSource, what's 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();
}
Could someone point me in the right direction?
EDIT
To clarify; I'm looking for something like this (the below will check field
in entity of type TSource
for 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();
}
I can then use it as follows
context.Set<TEntity>()
.Where(e => !e.AMT_ValidationStatus.Equals(ValidationStatus.FAILED.ToString()))
.Where(IsNull<TEntity>(f.Name))