2013-03-04 88 views
0

我有一種方法,我嘗試通過LINQ查詢返回一些數據庫結果,但是Visual Studio不允許我使用select語句。這是我到目前爲止有:不能在LINQ查詢中使用select

public static int GetCurrentUserDepartmentId(Guid userGuid) 
{ 
    int departmentId = -1; 

    using (PTMS_DataEntities entities = new PTMS_DataEntities()) 
    { 
     var userDepartment = from employee in entities.Employees 
          join user in entities.aspnet_Users 
          on employee.User_Id equals user.UserId 
          where employee.User_Id equals userGuid          

     departmentId = (int)userDepartment;     
    } 

    return departmentId; 
} 

然而,在LINQ段,我會像到如下:

from employee in entities.Employees 
join user in entities.aspnet_Users 
on employee.User_Id equals user.UserId 
where employee.User_Id equals userGuid 
select employee.Department_Id 

有,爲什麼我不是一個特別的原因被允許添加最後的選擇部分?

+0

你的意思是說你沒有得到intellisense中的select方法嗎? – 2013-03-04 17:11:23

+0

正確。當我嘗試手動添加它時,它也不喜歡它。 – 2013-03-04 17:12:53

+0

是命名空間System.Linq添加在頂部? – 2013-03-04 17:13:30

回答

2

糾正你

where employee.User_Id equals userGuid 

where employee.User_Id == userGuid 
+0

所以只是爲了澄清,==和等於工作類似於常規的C#代碼,這意味着等於等同於.Equals()?道歉,我在使用LINQ方面有點新鮮。 – 2013-03-04 17:16:09

+0

@Chris V.,* equals *是僅在查詢表達式的連接子句中使用的上下文關鍵字。 – aush 2013-03-04 17:19:06

+0

我相信,equals只用於linq內,因爲除了連接語法之外,==和.Equals是不同的機制,儘管 – AdamWhite 2013-03-04 17:19:15

2

的問題是與您的where子句:

var userDepartment = from employee in entities.Employees 
         join user in entities.aspnet_Users 
         on employee.User_Id equals user.UserId 
         where employee.User_Id equals userGuid 

應該是:

var userDepartment = from employee in entities.Employees 
         join user in entities.aspnet_Users 
         on employee.User_Id equals user.UserId 
         where employee.User_Id == userGuid 
         select employee.Department_Id 
+0

是不是隻用於數字數據?我的印象是Guids是字符串數據 – 2013-03-04 17:17:47

+0

@ChrisV。對於任何類型,'=='運算符都可以被重載。 – 2013-03-04 17:21:42

+0

@ChrisV。看看這個[C#區別'=='和.Equals()](http://stackoverflow.com/questions/814878/c-sharp-difference-between-and-equals) – psubsee2003 2013-03-04 17:22:07