Custom Method in LINQ to SQL query

前端 未结 3 1947
半阙折子戏
半阙折子戏 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:13

    Check this full article : What is and what isn't possible with linq

    Following is not possible

    // function used in filter
    static bool MyFunc(Nwind.Product p)
    {
      return p.ProductName.StartsWith("B");
    }
    // query that uses MyFunc
    var q = 
      from p in db.Products
      where MyPriceFunc(p.UnitPrice) > 30m
      select p
    

    It compiles with no errors, but when you execute it LINQ to SQL throws an exception saying: "Static method System.Boolean MyTest(LINQTest.Nwind.Product) has no supported translation to SQL."

    The exception is actually thrown when you try to fetch results from q (for example using the foreach statement), because LINQ to SQL attempts to convert the expression trees to T-SQL only when the results are needed and the query must be executed.

    To fix the example you can simply copy the code that checks whether product name starts with "B" to the where clause of the query and it would work fine.

提交回复
热议问题