使用通用列名称添加linq查询的where子句

时间:2015-12-20 08:58:12

标签: c# entity-framework linq

只有在泛型类型表上有列时,我才想在linq查询中添加where子句。

代码示例: 此函数对于模型中的所有表都是通用的。我想为所有包含" AccountId"的表格添加条件。列。

ruz$type <- "ruz"
dfr$val2 <- dfr$val2 * 100
dfr$type <- "dfr"
names(ruz) <- names(dfr)
df <- rbind(ruz, dfr)

ggplot(df, aes(date, val2, color = type), size = 1.5) + geom_line()

我需要像

这样的东西
public IQueryable RetrieveAll(params Expression>[] eagerProperties) { 
var entitySet = ResolveEntitySet(typeof(T));
var query = context.CreateQuery<T>(entitySet);
foreach (var e in eagerProperties)
{
     query = query.Expand(e);
} 
var type = typeof(T); 
var account =    type.GetProperty("AccountId"); 
if(account!=null) 
  { 
    query = query.where(x=>x...) 
  } 
return query

由于

1 个答案:

答案 0 :(得分:2)

您必须使用表达式树动态创建Where谓词,请查看以下代码:

public static IQueryable<T> RetrieveAll<T>(params Expression[] eagerProperties)
{
    var type = typeof(T);
    var entitySet = ResolveEntitySet(type);
    var query = context.CreateQuery<T>(entitySet);
    foreach (var e in eagerProperties)
    {
        query = query.Expand(e);
    }
    var account = type.GetProperty("AccountId");
    if (account != null)
    {
        Guid g = new Guid("3252353h....");
        var parameter = Expression.Parameter(type);
        var property = Expression.Property(parameter, account);
        var guidValue = Expression.Constant(g);

        var lambdaPredicate = Expression.Lambda<Func<T, bool>>(Expression.Equal(property, guidValue), parameter);
        return query.Where(lambdaPredicate);
    }
    return query;
}
相关问题