Custom Method in LINQ to SQL query

前端 未结 3 1942
半阙折子戏
半阙折子戏 2020-12-04 02:29

Is it possible to use custom method In query for example:

var result = from u in context.MyTable where MyMethod(u) == 10 select u;
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 03:17

    As Pranay explains, you cannot have a custom (C#) method as part of the LINQ to SQL query, because LINQ to SQL wouldn't be able to look at the expression tree of the method and so it cannot translate it to SQL.

    One option that you have is to write your function in SQL and store it as a SQL function on the SQL Server (possibly, you could also use SQL CLR, but I have not tried that). Then you can add the function to your DataContext type and LINQ to SQL will translate it to calls to the function on SQL server. Something like:

    var result = from u in context.MyTable 
                 where context.MyMethod(u) == 10 select u; 
    

    The problem, of course, is that you'll need to write the function in SQL (I think SQL CLR could also work - not sure about the performance and other possible complications though)

    I also wrote an article (some time ago) that shows how to do this when you write the "method" as an expression tree way (as a value of type Expression>), which is possible, because in this case, the code is compiled as an expression tree. However, there is some postprocessing that has to be done and you can still write just a single expression that can be easily inlined in the LINQ query.

提交回复
热议问题