【问题标题】:LINQ-to-SQL and Extension method in subQuerysubQuery 中的 LINQ-to-SQL 和扩展方法
【发布时间】:2009-04-15 20:00:51
【问题描述】:

我的扩展方法是:

public static IEnumerable<T> FilterCultureSubQuery<T>(this Table<T> t)
    where T : class
    {
      return t;
    }

我尝试在这个查询中使用它

var test = from p in t.Products
             select new
             {
               Allo = p,
               Allo2 = (from pl in t.ProductLocales.FilterCultureSubQuery()
                        select pl)
             };

我的方法扩展的签名应该是什么?我总是收到这个错误:

方法 'System.Collections.Generic.IEnumerable`1[ProductLocale] FilterCultureSubQuery[ProductLocale](System.Data.Linq.Table`1[ProductLocale])' 不支持对 SQL 的转换。

我也试过这个签名:

public static IQueryable<T> FilterCultureSubQuery<T>(this Table<T> t)
    where T : class
    {
      return t;
    }

我得到了这个错误:

方法 'System.Linq.IQueryable`1[ProductLocale] FilterCultureSubQuery[ProductLocale](System.Data.Linq.Table`1[ProductLocale])' 不支持 SQL 转换。

谢谢

【问题讨论】:

    标签: c# linq linq-to-sql extension-methods


    【解决方案1】:

    您的方法的签名很好。问题是,如前所述,它“没有支持的 SQL 转换”。

    LINQ 正在尝试将该语句转换为将发送到数据库的 SQL 行。该方法没有翻译。

    我建议使用 Where 子句重写过滤器。

    【讨论】:

      【解决方案2】:

      您的扩展方法没有问题。

      您收到该异常是因为您尝试在 LINQ-To-SQL 查询中使用自定义方法,而 LINQ-To-SQL 不知道您的方法的 SQL 转换。因此它无法从您的 LINQ 表达式构造 SQL 查询。

      解决方案是先获取数据,然后应用您的转换。

      【讨论】:

        【解决方案3】:

        当我在一个简单的查询中使用我的扩展方法时,它可以工作,但是当我在子查询中使用它时,它就不起作用了。有什么解决办法吗?

        工作

        var test = from pl in t.ProductLocales.FilterCultureSubQuery()  select pl;
        

        不工作

        var test = from p in t.Products
                   select new
                   {
                     Allo = p,
                     Allo2 = (from pl in t.ProductLocales.FilterCultureSubQuery()
                              select pl)
                   }; 
        

        我创建了一个新的扩展方法并重写了查询的表达式树。

        var test = (from p in t.Products
                       select new
                       {
                         Allo = p,
                         Allo2 = (from pl in t.ProductLocales.FilterCultureSubQuery()
                                  select pl)
                       }).ArrangeExpression(); 
        

        LINQ-TO-SQL 难以在子查询中使用扩展方法。使用重写表达式扩展方法,一切正常。

        还有其他解决方案吗?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多