微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 具有count()> 1的表达式树

我正在使用EF 6.1,我想使用以下SQL查询我的实体

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

这里的字段和实体都是可变的.如果两者都在编译时已知,我可以使用Context.Set< Entity>().GroupBy(e => e.Field).Where(f => f.Count()> 1).选择(f = > f.Key)

编辑
忘记提到该字段始终是字符串类型.

我认为可以使用表达式树,但我对此并不十分熟悉,学习曲线有点陡峭.

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();
        }

有人能指出我正确的方向吗?

编辑

澄清;我正在寻找这样的东西(下面将检查TSource类型的实体中的字段为null)

public Func<TSource,bool> IsNull<TSource>(string field)
        {
            var parameter = Expression.Parameter(typeof(TSource),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 })

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐