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

我想使用 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);

 }

有没有办法做到这一点,我可以使用字符串参数来定义要限制的对象的属性?


幕布斯6054654
浏览 74回答 2
2回答

慕姐8265434

您可以使用表达式树动态构建 Linq where 子句来过滤动态属性。我知道这可能需要消化很多东西,但是,就这样吧。将 StockItem 替换为 StockView DbSet 的类型[HttpGet("{searchText}/{filterType}")]&nbsp;public async Task<ActionResult<List<Stock>>> Get(string searchText, string filterType){&nbsp; &nbsp; var queryableStockView = this._context.StockView;&nbsp; &nbsp; // w =>&nbsp; &nbsp; var param = Expression.Parameter(typeof(StockItem), "w");&nbsp; &nbsp; var propertyInfo = typeof(StockItem).GetProperty(filterType);&nbsp; &nbsp; if (propertyInfo == null)&nbsp; &nbsp; &nbsp; &nbsp; throw new Exception($@"Property ""{property}"" was not found");&nbsp; &nbsp; // w.[filterType]&nbsp; &nbsp; var left = Expression.Property(param, propertyInfo);&nbsp; &nbsp; // searchText&nbsp; &nbsp; var right = Expression.Constant(searchText, typeof(string));&nbsp; &nbsp; // w.[filterType] == searchText&nbsp; &nbsp; var expression = Expression.Equal(left, right);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Bring it all together&nbsp; &nbsp; // Where(w => (w.[filterType] == searchText))&nbsp; &nbsp; var whereExpression = Expression.Call(&nbsp; &nbsp; &nbsp; &nbsp; typeof(Queryable),&nbsp; &nbsp; &nbsp; &nbsp; nameof(System.Linq.Enumerable.Where),&nbsp; &nbsp; &nbsp; &nbsp; new Type[] { queryableStockView.ElementType },&nbsp; &nbsp; &nbsp; &nbsp; queryableStockView.Expression,&nbsp; &nbsp; &nbsp; &nbsp; Expression.Lambda<Func<StockItem, bool>>(expression, new ParameterExpression[] { param })&nbsp; &nbsp; );&nbsp; &nbsp; // Run query against the database&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; var filteredItems = queryableStockView.Provider.CreateQuery<StockItem>(whereExpression);&nbsp; &nbsp; var v = await filteredItems.ToListAsync();&nbsp; &nbsp; return this.Ok(v);&nbsp;}动态生成的 Linq 表达式应该可以毫无问题地转换为 SQL。

12345678_0001

要做你想做的事情,你需要编写一堆映射代码。(超出范围,你需要展示你已经尝试过的内容)这样您就可以动态设置字段,执行原始 sql 会更容易。或者,您可以设置数据来支持您的搜索...见下文。[HttpGet("{searchText}/{filterType}")]&nbsp;public async Task<ActionResult<List<Stock>>> Get(string searchText, string filterType)&nbsp;{&nbsp; &nbsp; var v = await this._context.StockView&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Where(x => x.Type == filterType&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&& x.SearchField == searchText).TolistAsync();&nbsp; &nbsp; return this.Ok(v);&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP