2012-06-16 56 views
-1

Possible Duplicate:
Equivalent of SQL ISNULL in LINQ?
Using IsNull or select COALESCE in Linq..?LINQ不能用於「select isnull」查詢..?

我已經試過此查詢在LINQ:

string 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)"; 

     ArrayList allNames=null; 
     using (var context = new NewsReaderEntities()) 
     { 
      ObjectQuery<string> results = context.CreateQuery<string>(query); 
     // ObjectQuery<string> results1 = context.CreateQuery<string> 
      (query1,parameters); 
      foreach (string result in results) 
      { 
       allNames.Add(result); 

      } 
     } 

     return allNames; 



    } 

但它返回的錯誤:

linq 'ISNULL' cannot be resolved into a valid type or function. Near simple identifier,

我也試過這個查詢:

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管理中使用。有任何想法嗎?

+1

您是否嘗試過谷歌搜索「LINQ ISNULL」 - 它返回這太問題,我相信會回答你的問題 - HTTP:// stackoverflow.com/questions/413084/equivalent-of-sql-isnull-in-linq –

回答

0

見這個例子:

var query = from p in Pets select p; 
if (OwnerID != null) query = query.Where(x => x.OwnerID == OwnerID); 
if (AnotherID != null) query = query.Where(x => x.AnotherID == AnotherID); 
if (TypeID != null) query = query.Where(x => x.TypeID == TypeID); 

希望這有助於你