1

when we have two tables with one to zero or one relationship. there might be records in tableA with no corresponding record in tableB.
So the Join Operation results null values for these records. My Goal is to replace these Nulls with a defalut value.
My Question is How can we do this in Database Context And in C# Context(when we have standard c# collections instead of db tables) using linq?

Example Tables :

  tableA{id , name , info}
  tableB{id , tableAid , number}

Query:

var result= from a in tableA join b in tableB on b.tableAid equals a.id 
            select new {id = a.id , name = a.name , number = b.number }

number in the result may be null If there is no record in tableB for a specific record in tableA.
i need such a thing:

if(result[i].number==null)result[i].numer=1
Hamed
  • 117
  • 5
  • 17

2 Answers2

2

You need to use left join in linq for your scenario, After that @Patrick Hofman's code will work

var result= from a in tableA join b in tableB on b.tableAid equals a.id 
            into grp from c in grp.DefaultIfEmpty()
            select new {id = a.id , name = a.name , number = c != null ? (c.number ?? 0) : 0 }
Community
  • 1
  • 1
Palanikumar
  • 6,940
  • 4
  • 40
  • 51
1

If b is null, since it can't be found on the other end, you can use a null check with the ternary operator, possibly combined with a null-coalescing operator for b.number:

number = b != null ? (b.number ?? 0) : 0;
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325