defaultifempty throws "is not a sequence"

Jan 4, 2011 at 7:33 PM
Edited Jan 4, 2011 at 7:34 PM

The following query works fine:

    var test = from hr180 in context.hr180
                join pr153 in context.pr153 on hr180.cid equals pr153.cid180 into somePr153
                from allPr153 in somePr153.DefaultIfEmpty()
                select new
                {
                    hr180.clastname,
                    hr180.cfirstname,
                    hr180.cmi,
                    allPr153.yempcost,
                    allPr153.ystdamtpct
                };

But this query throws an exception:

    var test = from hr180 in context.hr180
                join pr153 in context.pr153 on hr180.cid equals pr153.cid180 into somePr153
                from allPr153 in somePr153.DefaultIfEmpty(new pr153())
                select new
                {
                    hr180.clastname,
                    hr180.cfirstname,
                    hr180.cmi,
                    allPr153.yempcost,
                    allPr153.ystdamtpct
                };

Here are the exception details:

System.Exception: The expression of type 'System.Collections.Generic.IEnumerable`1[Csi.Common.AccountingPlus.pr153]' is not a sequence

The only difference is that I tried to new up a pr153 object in the DefaultIfEmpty call..

Is this doable, or do I need to test allPr153 for null in the "select" portion of the query? In other words:

    var test = from hr180 in context.hr180
                join pr153 in context.pr153 on hr180.cid equals pr153.cid180 into somePr153
                from allPr153 in somePr153.DefaultIfEmpty()
                select new
                {
                    hr180.clastname,
                    hr180.cfirstname,
                    hr180.cmi,
                    yempcost = allPr153 == null ? 0 : allPr153.yempcost,
                    ystdamtpct = allPr153 == null ? 0 : allPr153.ystdamtpct
                };

I'd like to avoid that extra code if possible.

Thoughts?
Coordinator
Jan 5, 2011 at 12:06 AM

It seems that you cannot avoid having to test for the null value. 
I tested this scenario with Linq to Sql and Entity Framework – they both throw a NotSupportedException when trying to pass a new object instance to the DefaultIfEmpty method.  Ideally, the IQToolkit would also provide a NotSupportedException but unfortunately… it apparently isn’t handling this type of scenario.

Jan 5, 2011 at 1:48 AM

That's what I was afraid of. Thanks for the confirmation. One of the last things I read today said something about not having to check for null -- that allPr153 would automatically be initialized to some default value. I didn't have time to test it though. Will probably do that tomorrow morning out of curiosity.