【问题标题】:Using IsNull or select COALESCE in Linq..? [duplicate]在 Linq 中使用 IsNull 或选择 COALESCE ..? [复制]
【发布时间】:2012-06-16 14:17:25
【问题描述】:

可能重复:
Equivalent of SQL ISNULL in LINQ?

我有 3 个这样的表:

评论表:

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

学生桌

sid     firstname   lastname
1         john       adam
2         joan       adam

教授表:

pid    firstname   lastname
1       mark        abram
2       sean        hoak

我想进行查询,结果返回如下:

firstname    lastname
mark          abram
john          adam
sean          hoak

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

我尝试了以下方法:

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)

但没有用

然后其他人提供了这个解决方案查询

IsNull 查询

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)

合并:

  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

在 SQL 管理中都可以正常工作,但在 Linq 中:

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

我尝试将它自己转换为:

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
  };

但它返回 null

有什么想法吗?

【问题讨论】:

    标签: sql sql-server linq tsql linq-to-sql


    【解决方案1】:

    您在tmp1 附近似乎有错字,您应该使用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
          };
    

    【讨论】:

    • 发布错误以解决特定问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 2012-06-12
    • 2010-10-22
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多