-3

Possible Duplicate:
Equivalent of SQL ISNULL in LINQ?

I have 3 tables like this :

comment table :

commentId pid    sid       text      vid
1          1     null    comment 1    1
2         null    1     comment 2    1
3          2     null    comment 3    1

student table

sid     firstname   lastname
1         john       adam
2         joan       adam

professor table :

pid    firstname   lastname
1       mark        abram
2       sean        hoak

I want to make a query so the result to return like this :

firstname    lastname
mark          abram
john          adam
sean          hoak

m

if (select query ==null) then (selec query 1) else select (query 2)

i tried the following :

if((select pid from comment==null)
then select student.firstname , student.lastname from student where sid in (select sid from comment where vid=1)

else
(select professor.firstname ,professor.lastname from professor where pid in (select pid from comment where vid=1)

but with no use

then others provided this solution queries

IsNull Query

SELECT ISNULL(P.firstname, s.firstname) AS Expr1,ISNULL(P.lastname, s.lastname) AS Expr2
FROM comment AS C 
    LEFT OUTER JOIN professor AS P ON P.ID = C.PID 
    LEFT OUTER JOIN student AS s ON s.ID = C.SID
WHERE (C.VID = 2)

COALESCE:

  SELECT COALESCE(p.firstname, s.firstname), COALESCE(p.lastname, s.lastname)
  FROM comment c
  LEFT JOIN Professor p
  ON c.pid = p.id
 LEFT JOIN Student s
  ON c.sid = s.id
   WHERE c.vid = 2

both works fine in SQL Management , but in Linq with the:

ObjectQuery<string> results1 = context.CreateQuery<string>(query1, parameters) 

I've tried to convert it my self to :

var qry = from c in ctx.comment
  join p in ctx.professor
  on c.PID equals p.ID into tree
  join s in ctx.student
  on c.SID equals s.ID into tree1
  where c.VID == vID
  from tmp in tree.DefaultIfEmpty()
  from tmp1 in tree.DefaultIfEmpty()
  select new
  {
      Firstnmae = tmp.firstname ?? tmp1.firstname,
      LastName = tmp.lastname ?? tmp1.lastname
  };

but it returns null

Any ideas please?

Community
  • 1
  • 1
M.A.
  • 1
  • 3
  • 9

1 Answers1

4

It seems you have a typo near tmp1, you should do tree1.DefaultIfEmpty()

      var qry = from c in ctx.comment
      join p in ctx.professor
      on c.PID equals p.ID into tree
      join s in ctx.student
      on c.SID equals s.ID into tree1
      where c.VID == vID
      from tmp in tree.DefaultIfEmpty()
      from tmp1 in tree1.DefaultIfEmpty()
      select new
      {
          Firstnmae = tmp.firstname ?? tmp1.firstname,
          LastName = tmp.lastname ?? tmp1.lastname
      };
Sebastian Piu
  • 7,838
  • 1
  • 32
  • 50