2013-08-28 291 views
0

我有一個包含用戶數據連接兩個表有兩個外鍵

Users(userID, name , email ,......) 

和我哈瓦包含其它表的表:

在UserFriends表
Userfriends(UserFriendID,Fk_UserSendReqID,FK_UserRecieveReqID,IsAccepted,....) 

有連接兩個外鍵這張表與用戶表 我想寫一個查詢與LINQ選擇用戶的朋友userId=2 我寫這個查詢,但它是錯的

var n = from u in DataContext.Context.Users 
       join uf in DataContext.Context.UsersFriends 
       on u.UserID equals uf.UserSendReqID 
       join uf2 in DataContext.Context.UsersFriends 
       on u.UserID equals uf2.UserRecieveReqID 
       where (uf.UserSendReqID == 2|| uf.UserRecieveReqID == 2) 
       && uf.IsAccepted == true 
       select new 
       { 
        name = u.FirstName + " " + u.LastName 
       }; 

回答

0

由於有對Users表2個的外鍵,你必須加入Users表而不是UsersFriends

var userID = 2; 
var n = from u in DataContext.Context.Users 
      join uf in DataContext.Context.UsersFriends 
      on u.UserID equals uf.UserSendReqID 
      join u in DataContext.Context.Users 
      on u2.UserID equals uf.UserRecieveReqID 
      where (uf.UserSendReqID == userID || uf.UserRecieveReqID == userID) 
      && uf.IsAccepted == true 
      select new 
      { 
       //if UserSendReqID == userID, then select for u, else u2 
       name = (uf.UserSendReqID == userID) 
          ? (u.FirstName + " " + u.LastName) 
          : (u2.FirstName + " " + u2.LastName) 
      }; 
0
var n = DataContext.Context.Users 
        .Where(u=>DataContext.Context.UsersFriends 
          .Where(uf=>(uf.UserSendReqID == 2 || 
             uf.UserReceiveReqID == 2) && uf.IsAccepted) 
          .Any(uf=>uf.UserFriendID == u.userID)) 
        .Select(u=> new { 
           Name = u.FirstName + " " + u.LastName          
           }); 

或者使用Join

var n = DataContext.Context.Users 
        .Join(DataContext.Context.UsersFriends 
            .Where(uf=>(uf.UserSendReqID == 2 || 
             uf.UserReceiveReqID == 2) && uf.IsAccepted), 
         x=>x.userID, x=>x.UserFriendID, (x,y)=>x) 
        .Select(u=> new { 
           Name = u.FirstName + " " + u.LastName          
           }); 

表達查詢:

var n = from u in DataContext.Context.Users 
     join uf in DataContext.Context.UsersFriends on u.userID equals uf.UserFriendID 
     where (uf.UserSendReqID == 2 || uf.UserReceiveReqID == 2) && uf.IsAccepted 
     select new { 
       Name = u.FirstName + " " + u.LastName 
       };