自定义方法的 LINQ to SQL 转换为 SQL

发布于 2024-08-26 02:22:26 字数 697 浏览 5 评论 0原文

有没有办法将表达式转换为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小…楫夜泊 2024-09-02 02:22:26

最实用的选择可能是组合:

// build the core query
var list = from i in dataContext.items
           // most of your query
           select ...

// compose the value-filter if required
switch(someOperator) {
    case "=": list = list.Where(row => row.value1 == row.value2); break;
    case ">": list = list.Where(row => row.value1 > row.value2); break;
    case "<": list = list.Where(row => row.value1 < row.value2); break;
}

// now use "list"

如果您需要可重用的东西,您将不得不亲自构建(并且可能解析)表达式树(System.Linq.Expression) 。不是微不足道的。

The most pragmatic option may be compositon:

// build the core query
var list = from i in dataContext.items
           // most of your query
           select ...

// compose the value-filter if required
switch(someOperator) {
    case "=": list = list.Where(row => row.value1 == row.value2); break;
    case ">": list = list.Where(row => row.value1 > row.value2); break;
    case "<": list = list.Where(row => row.value1 < row.value2); break;
}

// now use "list"

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文