2015-10-06 64 views
-1

我有兩個表:如何將這個Sql查詢轉換爲Linq?

User 
    (
    UserId int primary key, 
    Firstname, 
    Lastname, ... 
    info ... 
) 

Friend 
    (
    User1Id int, 
    User2Id int, 
    Status varchar(1), -- '1' is friend, '0' is pending friend request 
    primary key(User1Id,User2Id) 
) 

(User1Id, User2Id)是外鍵引用[User]表。

我有這樣的SQL查詢:

select * from User 
where UserId in 
(
    (select User1Id from Friend where User2Id='@id' and Status='1') 
    union 
    (select User2Id from Friend where User1Id='@id' and Status='1') 
) 

它成功地執行並返回數據如預期。

但是,在從SQL轉換到Linq時,我遇到了in問題。我無法使用.Contains(),因爲數據類型無法轉換。我該如何翻譯?

我嘗試這樣的Linq代碼:

var query = (from u in Users 
      where u.UserId.Contains(
       (from f in Friends 
        where f.User1Id==1 && Status=='1' 
        select f.User2Id 
       ).Union(from f in Friends 
         where f.User2Id==1 && Status=='1' 
         select f.User1Id)) 
      select u); 

,但我得到這個錯誤: 「數據類型不能轉換」

.Contains() cannot use with Int and IQuery

+0

* *?那是什麼意思? –

+0

@ypercube我不知道,但當執行它有這個錯誤。 .Contains()不能與Int和IQuery一起使用 ?? – Jen

+0

好吧,您既沒有提供產生錯誤的代碼,也沒有提供您得到的實際錯誤消息。編輯問題,添加它們,問題可能會重新打開。 –

回答

1
internal class Program 
    { 
     private static void Main(string[] args) 
     { 
      List<User> users = new List<User>(); 
      users.Add(new User() { id = 1, name = "1" }); 
      users.Add(new User() { id = 2, name = "2" }); 
      users.Add(new User() { id = 3, name = "3" }); 

      List<Friend> friends = new List<Friend>(); 
      friends.Add(new Friend() { User1Id = 2, User2Id = 1 }); 
      friends.Add(new Friend() { User1Id = 1, User2Id = 3 }); 
      friends.Add(new Friend() { User1Id = 2, User2Id = 3 }); 

       var query = users.Where(q => (from f1 in friends where`f1.User1Id == 1 select f1.User2Id).Union(from f1 in friends where f1.User2Id ==` 1 select f1.User1Id).Contains(q.id)); 
     } 
    } 

    public class User 
    { 
     public int id { get; set; } 

     public string name { get; set; } 
    } 

    public class Friend 
    { 


     public int User1Id { get; set; } 

     public int User2Id { get; set; } 
    } 
+0

我試過了,但我無法收到任何結果,儘管沒有錯誤 – Jen

+0

是的,這是一個錯誤。我編輯了我的解決方案 – GasDev

+0

我也無法收到結果:( – Jen