简体   繁体   English

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

[英]LINQ to SQL translation to SQL of custom method

Is there a way to translate an expression to SQL to use with LINQ to SQL ? 有没有办法将表达式转换为SQL以与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. 这不起作用,因为很明显, MyComparer不会转换为SQL。

Maybe this is a twisted question, but how can I translate this method to SQL or is this possible? 也许这是一个扭曲的问题,但我怎样才能将此方法转换为SQL或这可能吗?

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 ). 如果你需要一些可重复使用的东西,你将不得不自己动手(并且可能正在解析)表达式树( System.Linq.Expression )。 Not trivial. 不是微不足道的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM