我正在使用 EF 6.1,我想使用以下 SQL 查询我的实体
SELECT field, count(*)
FROM entity
GROUP BY field
HAVING COUNT(*) > 1
这里都是field
和 entity
是可变的。如果两者都在编译时已知,我可以使用 Context.Set<Entity>().GroupBy(e => e.Field).Where(f => f.Count() > 1).Select(f => f.Key)
编辑
忘了说 field
始终是字符串类型。
我认为可以使用表达式树,但我对此不是很熟悉并且学习曲线有点陡峭。
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();
}
有人能给我指出正确的方向吗?
编辑
澄清;我正在寻找这样的东西(下面将检查 field
类型的实体中的 TSource
是否为 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();
}
然后我可以按如下方式使用它
context.Set<TEntity>()
.Where(e => !e.AMT_ValidationStatus.Equals(ValidationStatus.FAILED.ToString()))
.Where(IsNull<TEntity>(f.Name))
最佳答案
好的,明白了
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 })
关于c# - count() > 1 的表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38395531/