简体   繁体   English

在WHERE子句中具有动态列名称的MVC Linq查询

[英]MVC Linq Query with dynamic column name in WHERE clause

I have a number of calls for the same query but with slightly different WHERE clause, does anyone know if it's possible to pass a variable as the column name as I can't seem to acheive it. 我对相同的查询有很多调用,但是WHERE子句略有不同,有人知道我是否可以实现将变量作为列名来传递。

I know the below isn't correct but just to give you an idea of what i'm trying to acheive. 我知道以下内容是不正确的,只是让您对我要达到的目标有所了解。

public EmailUserListViewModel EmailUserListData(int CaseId, string ColumnName)
{
    CaseId = CaseId,
    EmailUserList = (from u in efContext.PgsUsers
                        where ColumnName == true
                        orderby u.FirstName, u.LastName
                        select new EmailUserListModel
                        {
                            UserId = u.Id,
                            Name = ((u.FirstName == null) ? "" : u.FirstName) 
                                   + ((u.LastName == null) ? "" : " " + u.LastName),
                            Email = u.Email,
                            Checked = false

                        }).ToList()
    };
}

I suppose you could use Reflection to dynamically retrieve the value of the property 我想您可以使用Reflection动态地获取属性的值

from u in efContext.PgsUsers where (typeof(PgsUser).GetProperty(ColumnName).GetValue(u) as bool) == true

or 要么

from u in efContext.PgsUsers where (u.GetType().GetProperty(ColumnName).GetValue(u) as bool) == true

You could write such method: 您可以编写这样的方法:

public Expression<Func<T, bool>> getExpression<T>(string columnName)
{
    var param = Expression.Parameter(typeof(T));
    var equal = Expression.Equal(Expression.Property(param, columnName), Expression.Constant(true));
    return (Expression<Func<T, bool>>)Expression.Lambda(equal, param);
}

and use it in where: 并在以下地方使用:

where getExpression<YourType>("ColumnName")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM