自定义方法的 LINQ to SQL 转换为 SQL
有没有办法将表达式转换为 SQL 以便与 LINQ to SQL 一起使用?
例如,我有一个比较两个值的方法。
示例:
MyComparer.Compare(value1, value2, ">") return value1 > value2
MyComparer.Compare(value1, value2, "=") return value1 == value2
MyComparer.Compare(value1, value2, "<=") return value1 <= value2
我想要这样的查询:
var list = from i in dataContext.items
where MyComparer.Compare(i.value, someValue, "some operator")
select ...
这不会起作用,因为显然 MyComparer
不会转换为 SQL。
也许这是一个扭曲的问题,但是我如何将此方法转换为 SQL 或者这可能吗?
Is there a way to translate an expression to SQL to use with LINQ to SQL?
For example I have a method that compares two values.
Example:
MyComparer.Compare(value1, value2, ">") return value1 > value2
MyComparer.Compare(value1, value2, "=") return value1 == value2
MyComparer.Compare(value1, value2, "<=") return value1 <= value2
And I would like a query like:
var list = from i in dataContext.items
where MyComparer.Compare(i.value, someValue, "some operator")
select ...
This won't work because, obviously, MyComparer
doesn't translate to SQL.
Maybe this is a twisted question, but how can I translate this method to SQL or is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最实用的选择可能是组合:
如果您需要可重用的东西,您将不得不亲自构建(并且可能解析)表达式树(
System.Linq.Expression
) 。不是微不足道的。The most pragmatic option may be compositon:
If you need something re-usable, you're going to have to get your hands dirty building (and probably parsing) expression-trees (
System.Linq.Expression
). Not trivial.