用两个外键加入两个表

时间:2013-08-28 06:02:21

标签: c# asp.net sql linq

我有一个包含用户数据的表

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

我还有一个包含以下内容的表:

Userfriends(UserFriendID,Fk_UserSendReqID,FK_UserRecieveReqID,IsAccepted,....)

在UserFriends表中有两个外键将此表与users表连接 我想用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
                };

2 个答案:

答案 0 :(得分: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)
            };

答案 1 :(得分: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
               };