我正在使用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();
}
有人能指导我走向正确的方向吗?
编辑
澄清一下;我正在寻找像这样的东西(以下内容将检查TSource
类型实体中的field
是否为空)。
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))