MVC Linq Query在WHERE子句中使用动态列名称

时间:2017-01-19 12:40:13

标签: c# .net asp.net-mvc linq

我对同一个查询有很多调用但是WHERE子句略有不同,有没有人知道是否可以将变量作为列名传递,因为我似乎无法实现它。

我知道下面的内容不正确,只是为了让您知道我想要实现的目标。

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()
    };
}

2 个答案:

答案 0 :(得分:2)

我想你可以使用Reflection来动态检索属性的值

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

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

答案 1 :(得分:1)

你可以写这样的方法:

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);
}

并在其中使用:

where getExpression<YourType>("ColumnName")