0

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

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

我有另一个表,其中包含:

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

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

2 回答 2

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
               };
于 2013-08-28T09:41:53.757 回答
0

As there are 2 foreign keys for Users table, you have to join Users table instead of 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)
            };
于 2013-08-28T06:08:37.363 回答