c# - count() > 1 的表达式树

标签 c# entity-framework linq

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

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

这里都是fieldentity是可变的。如果两者都在编译时已知,我可以使用 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.NameTEntity 中属性的名称)

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/

相关文章:

c# - 多个独立的注册和登录表单 .NET Identity 2.0

c# - Visio - 检查形状是否已连接

c# - Entity Framework 多对多数据不持久

c# - 每个 ID 删除许多记录 - MVC C#

entity-framework - EF 代码第一个整数鉴别器列

xml - LINQ to XML 和 Distinct 自定义类

c# - Linq 选择 : Set specific value for first occurrence only

C# 如何从进程中检索代码然后运行它?

c# - 从客户端接收文件并在 C# 中保存到服务器中的文件

c# - IEnumerable<T> 是否存储稍后调用的函数?