【问题标题】:Linq to SQL attempting left join with DefaultIfEmpty() causing Unsupported overload used for query operator 'DefaultIfEmpty'. errorLinq to SQL 尝试使用 DefaultIfEmpty() 进行左连接,导致用于查询运算符“DefaultIfEmpty”的不受支持的重载。错误
【发布时间】:2015-02-27 23:19:39
【问题描述】:

这是我第一次尝试通过 linq 进行左连接,我查看了堆栈溢出和谷歌,但我尝试过的一切都没有奏效(很可能是由于我自己缺乏理解)。我正在尝试执行以下查询:

IQueryable<MyType> pQ = (from prd in dc.ProductDatas 
join cc in dc.CategoryProducts.DefaultIfEmpty(defaultCP) 
on prd.ProductID equals cc.ProductID 
where cc.CatID == CatID
orderby cc.OrdWithinInCategory 
select prd);

我将 defaultCP 定义为:

CategoryProduct defaultCP = new CategoryProduct {ID = 1,CatID = CatID, OrdWithinInCategory = 999};

我收到以下错误:

用于查询运算符“DefaultIfEmpty”的重载不受支持。

说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.NotSupportedException:不支持的重载用于查询运算符“DefaultIfEmpty”。

我的代码中是否有任何明显的错误,或者我需要完全尝试不同的方法。非常感谢任何帮助。

【问题讨论】:

  • 您的where 子句将取消左连接的效果,因为cc.CatID 为null 的行将被删除。您的were 子句是否正确?系统抱怨defaultCP。使用普通的DefaultIfEmpty() 重载,您看到的错误应该会消失(不过,您可能会得到一个新错误)。
  • 是否将 defaultCP 的 CatID 指定为 CatID 会阻止删除行,因为它们将等于我检查的值?
  • 它在内存中,但据我所知,SQL中没有对应的构造。
  • 啊!谢谢,如果我想出一个问题,我会继续调查问题并发布答案!

标签: c# linq-to-sql left-join


【解决方案1】:

使用 AsEnumerable()。

CategoryProduct defaultCP = new CategoryProduct {ID = 1,CatID = CatID, OrdWithinInCategory = 999};

IQueryable<MyType> pQ = (from prd in dc.ProductDatas 
                        join cc in dc.CategoryProducts.DefaultIfEmpty(defaultCP) 
                           on prd.ProductID equals cc.ProductID 
                        where cc.CatID == CatID
                        orderby cc.OrdWithinInCategory 
                        select prd)
               .AsEnumerable()
               .DefaultIfEmpty(defaultCP).First();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    相关资源
    最近更新 更多