如何解决如何编写sql可转换表达式
让我说一个这样的例子:
我有很多型号。每个模型在某处都有location
,但在不同的地方,例如:
foo.location
或foo.bar.location
。现在,我想从数据库中按位置过滤一些对象,例如
var firstLocation = new Location(5,10);
var secondLocation = new Location(20,15);
var results = dbSet.Where(x =>
x.foo.location.xcord >= firstLocation.xcord && x.foo.location.xcord <= secondLocation.xcord &&
x.foo.location.ycord >= firstLocation.ycord && x.foo.location.ycord <= secondLocation.ycord
)
现在我想在其中提取此表达式的函数返回到类似于基于选择器的表达式的函数,该选择器显示内部对象在何处是位置对象:
dbSet.Where(GetLocationExpression(x => x.foo.bar,firstLocation,secondLocation))
如何实现?我使用EF Core,希望将其转换为sql。
我尝试过:
private Expression<Func<T,bool>> GetLocationExpression<T>(Func<T,Location> locationSelector,Location firstLocation,Location secondLocation)
{
return x =>
locationSelector(x).xcord >= firstLocation.xcord && locationSelector(x).xcord <= secondLocation.xcord
&&
locationSelector(x).ycord >= firstLocation.ycord && locationSelector(x).ycord <= secondLocation.ycord
}
但是它引发错误,该查询无法转换为SQL。 我还想在其中添加一些内容,例如:
dbSet.Where(x => x.Name = "something" && GetLocationExpression(x => x.foo.bar,secondLocation))
或者只是GetLocationExpression方法中的可选参数,用于任何其他过滤器
解决方法
将LINQKit用于此类任务,它将自动执行表达式替换。
private Expression<Func<Location,Location,bool>> GetLocationExpression<T>()
{
return (locationSelector,firstLocation,secondLocation) =>
locationSelector.xcord >= firstLocation.xcord && locationSelector.xcord <= secondLocation.xcord
&& locationSelector.ycord >= firstLocation.ycord && locationSelector.ycord <= secondLocation.ycord
}
和用法:
dbSet
.AsExpandable() // important,we have to switch to LINQKit expression preprocessor
.Where(x => x => x.Name = "something"
&& GetLocationExpression().Invoke(x.foo.bar,secondLocation))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。