0

I am working on a WinForms project which requires to use Linq-To-Sql. I have been able to create my DataContext using the SqlMetal tool, and make some queries. But right now I have a problem that I havent been able to solve.

I am trying to make a LEFT OUTER JOIN as following:

MyDatabase db = new MyDatabase(...);

 var query = from p in db.ParentTable
             join t in db.ChildTable on new {A = p.child_ID, B = p.OtherID}
             equals new {A = t.ID, B = t.OtherID} into j1
             from c in j1.DefaultIfEmpty()
             select new
             {
                  ...
             };

When I write this query an error is raised at compile-time in the join word:

The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'

I know this error is caused by the comparison between p.child_ID and t.ID since p.child_ID is int? and t.ID is int. But, How can I solve this? How can I perform the LEFT OUTER JOIN without having this error??

p.child_ID is int? since this column is marked as IS NULL in SQL.

Hope someone can help me, thanks in advance.

Dante
  • 3,208
  • 9
  • 38
  • 56

2 Answers2

6

You can use GetValueOrDefault() method. It retrieves the value of the current Nullable object, or the object's default value.

In terms of your example :

var query = from p in db.ParentTable
            join t in db.ChildTable on new {A = p.child_ID.GetValueOrDefault(0), B = p.OtherID}
            equals new {A = t.ID, B = t.OtherID} into j1
            from c in j1.DefaultIfEmpty()
            select new
            {
                ...
            };

If the p.child_ID become null than it will return 0. Hope this will help !!

Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32
4

The first problem was that the property names should be the same as said casperOne♦, but the second problem is that you're comparing a nullable-int, p.child_ID, with a non-nullable-int, t.ID. So you could use the null-coalescing operator in this way:

(int)(p.child_ID ?? default(int))

In this case returns p.child_ID if it isn't null else returns default(int), that is 0.

The query will be:

var query = from p in db.ParentTable
            join t in db.ChildTable on new {A = (int)(p.child_ID ?? default(T)), B = p.OtherID}
            equals new {A = t.ID, B = t.OtherID} into j1
            from c in j1.DefaultIfEmpty()
            select new
            {
               //...
            };
Omar
  • 16,329
  • 10
  • 48
  • 66