简体   繁体   English

C# Linq - 根据用户输入创建动态 select 查询

[英]C# Linq - Create a dynamic select query based on user input

Use Case: User needs to be able to select a field of input to review.用例:用户需要能够对 select 的输入字段进行审核。 This field request is then passed through the query which then returns the lists of inputs by the user for review.然后该字段请求通过查询传递,然后返回用户输入的列表以供查看。 Basically, a dynamic Select Statement in SQL where the FROM column is a variable defined by the user.基本上,SQL 中的动态 Select 语句,其中 FROM 列是用户定义的变量。

Method: Using C# and Linq I've written the following Linq Query to return the data, however, I'm not able to swap the actual field name in the query with a variable that has been set by the user.方法:使用 C# 和 Linq 我编写了以下 Linq 查询以返回数据,但是,我无法将查询中的实际字段名称与用户设置的变量交换。

Research: I've reviewed a dozen or so similar questions and articles and they all seem far more complicated than what I'm trying to accomplish and they don't seem to answer the question I have fully;研究:我已经回顾了十几个类似的问题和文章,它们似乎都比我试图完成的要复杂得多,而且它们似乎没有完全回答我的问题; that or I'm just not understanding what the solution actually is.那或者我只是不了解解决方案实际上是什么。 I've tried playing around with Dynamic Linq without much luck and using Expression Trees seems far more complicated that what I'm hoping is actually necessary.我试过玩 Dynamic Linq ,但运气不佳,使用表达式树似乎比我希望的实际需要复杂得多。

Explicitly Defined Field Select:显式定义字段 Select:

                    var Values = conn.Table<DataTable>()
                                      .Where(t => t.User_ID == ID)
                                      .Select(t => FieldName).Distinct().ToList();

Variable Field Select可变字段 Select

                   //allowing the user to set the value
                   string UserSelectedField = y_List[0].ToString(); 
                   var Values = conn.Table<DataTable>()
                                    .Where(t => t.User_ID == ID)
                                    .Select(t => @UserSelectedField).Distinct().ToList();

In the first query I get the results I'm looking for, but it is only able to return the values from the field typed in the code.在第一个查询中,我得到了我正在寻找的结果,但它只能从代码中键入的字段返回值。

The Second returns the object name like {FieldName = FieldName}.第二个返回 object 名称,如 {FieldName = FieldName}。

I've also tried just concatenating this in the query, but that didn't work.我也试过在查询中连接它,但这没有用。 Figured it wouldn't, but was worth a shot.认为它不会,但值得一试。

You have to write own extension, limitation here that you have to know type of the field:您必须在此处编写自己的扩展名和限制,您必须知道字段的类型:

public static class MyExtensions
{
    public class DynamicHelper<T>
    {
        private IQueryable<T> _query;

        internal DynamicHelper(IQueryable<T> query)
        {
            _query = query;
        }

        public IQueryable<TResult> SelectByFieldName<TResult>(string fieldName)
        {
            return MyExtensions.SelectByFieldName<T, TResult>(_query, fieldName);
        }
    }

    public static DynamicHelper<T> Dynamic<T>(this IQueryable<T> query)
    {
        return new DynamicHelper<T>(query);
    }

    private static IQueryable<TResult> SelectByFieldName<T, TResult>(IQueryable<T> query, string fieldName)
    {
        var param = Expression.Parameter(typeof(T), "e");
        Expression body = Expression.PropertyOrField(param, fieldName);
        if (body.Type != typeof(TResult))
            body = Expression.Convert(body, typeof(TResult));
        var lambda = Expression.Lambda<Func<T, TResult>>(body, param);
        return query.Select(lambda);
    }
}

And usage和用法

string UserSelectedField = y_List[0].ToString(); 
var Values = conn.Table<DataTable>()
   .Where(t => t.User_ID == ID)
   .Dynamic().SelectByFieldName<string>(UserSelectedField)
   .Distinct()
   .ToList();

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

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