2 回答
![?](http://img1.sycdn.imooc.com/5333a1d100010c2602000200-100-100.jpg)
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。
![?](http://img1.sycdn.imooc.com/54584f850001c0bc02200220-100-100.jpg)
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);
}
- 2 回答
- 0 关注
- 137 浏览
添加回答
举报