加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:00:45 所属栏目:百科 来源:网络整理
导读:我正在使用EF 6.1,我想使用以下SQL查询我的实体 SELECT field,count(*) FROM entityGROUP BY fieldHAVING COUNT(*) 1 这里的字段和实体都是可变的.如果两者都在编译时已知,我可以使用Context.Set Entity().GroupBy(e = e.Field).Where(f = f.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 })

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读