为了账号安全,请及时绑定邮箱和手机立即绑定

C# 使用字符串参数来定义对象列表中要过滤的属性

C# 使用字符串参数来定义对象列表中要过滤的属性

C#
幕布斯6054654 2023-09-16 15:07:03
我想使用 filterType 参数来定义 Stock 对象上要过滤的属性。[HttpGet("{searchText}/{filterType}")] public async Task<ActionResult<List<Stock>>> Get(string searchText, string filterType) {    List<Stock> v = await this._context.StockView.Where(w => w.[filterType] == searchText).ToListAsync();    return this.Ok(v); }有没有办法做到这一点,我可以使用字符串参数来定义要限制的对象的属性?
查看完整描述

2 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

您可以使用表达式树动态构建 Linq where 子句来过滤动态属性。


我知道这可能需要消化很多东西,但是,就这样吧。将 StockItem 替换为 StockView DbSet 的类型


[HttpGet("{searchText}/{filterType}")] 

public async Task<ActionResult<List<Stock>>> Get(string searchText, string filterType)

{

    var queryableStockView = this._context.StockView;


    // w =>

    var param = Expression.Parameter(typeof(StockItem), "w");


    var propertyInfo = typeof(StockItem).GetProperty(filterType);

    if (propertyInfo == null)

        throw new Exception($@"Property ""{property}"" was not found");


    // w.[filterType]

    var left = Expression.Property(param, propertyInfo);


    // searchText

    var right = Expression.Constant(searchText, typeof(string));


    // w.[filterType] == searchText

    var expression = Expression.Equal(left, right);

    

    // Bring it all together

    // Where(w => (w.[filterType] == searchText))

    var whereExpression = Expression.Call(

        typeof(Queryable),

        nameof(System.Linq.Enumerable.Where),

        new Type[] { queryableStockView.ElementType },

        queryableStockView.Expression,

        Expression.Lambda<Func<StockItem, bool>>(expression, new ParameterExpression[] { param })

    );


    // Run query against the database                                     

    var filteredItems = queryableStockView.Provider.CreateQuery<StockItem>(whereExpression);


    var v = await filteredItems.ToListAsync();


    return this.Ok(v);

 }

动态生成的 Linq 表达式应该可以毫无问题地转换为 SQL。


查看完整回答
反对 回复 2023-09-16
?
12345678_0001

TA贡献1802条经验 获得超5个赞

要做你想做的事情,你需要编写一堆映射代码。(超出范围,你需要展示你已经尝试过的内容)


这样您就可以动态设置字段,执行原始 sql 会更容易。


或者,您可以设置数据来支持您的搜索...见下文。


[HttpGet("{searchText}/{filterType}")] 

public async Task<ActionResult<List<Stock>>> Get(string searchText, string filterType)

 {

    var v = await this._context.StockView

              .Where(x => x.Type == filterType 

                       && x.SearchField == searchText).TolistAsync();


    return this.Ok(v);

 }


查看完整回答
反对 回复 2023-09-16
  • 2 回答
  • 0 关注
  • 69 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信