2012-06-16 41 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); 

希望这有助于你