【问题标题】:add where clauses to linq query with generic column name使用通用列名将 where 子句添加到 linq 查询
【发布时间】:2015-12-20 21:07:38
【问题描述】:

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

代码示例: 此函数对模型中的所有表都是通用的。我想为所有具有“AccountId”列的表格添加 where 条件。

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

我需要类似的东西

Guid g = new Guid("3252353h....")
query.where(x=>x.AccountId == g)

谢谢

【问题讨论】:

  • 我认为你在问什么有点不清楚。你能用更多解释编辑你的问题吗?
  • 好吧,如果您在每次调用时都执行“new Guid”,您将始终返回 null。

标签: c# entity-framework linq


【解决方案1】:

您必须使用表达式树动态创建 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;
}

【讨论】:

  • 谢谢!你帮了我很多
猜你喜欢
  • 1970-01-01
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 2018-08-14
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多