我该如何编写这个嵌套查询?

时间:2011-03-16 16:15:43

标签: sql linq-to-sql wcf-ria-services

我正在努力编写一个查询,该查询依赖于具有自己的查询操作的两个表的结果。

任何人都可以帮助我吗?


我的工作如下:

    public IQueryable<Message> GetMessages(int user_id)
    {
        // Get MessageReceiver tables that share receiver id
        IQueryable<MessageReceiver> messageReceivers = GetMessageReceivers().Where(messageReceiver => messageReceiver.receiver_id == user_id);

        List<Message> messages = new List<Message>();
        foreach (MessageReceiver messageReceiver in messageReceivers)
        {
            foreach (Message message in DataContext.Messages)
            {
                if (message.id == messageReceiver.message_id)
                {
                    messages.Add(message);
                }
            }
        }

        return messages.AsQueryable<Message>();
    }

此致 斯科特尼姆罗德

1 个答案:

答案 0 :(得分:0)

看到MessageRecievers是从与Message相同的数据上下文加载的,我们可以在同一个查询中加入它们。

public IQueryable<Message> GetMessages(int user_id)
{    
    // Get MessageReceiver tables that share receiver id
    var messageReceivers = GetMessageReceivers().Where(messageReceiver => messageReceiver.receiver_id == user_id);

    // get all messages that have been recieved by a user
    var messages = from m in DataContext.Messages
                   join r in messageReceivers
                   on m.id equals r.message_id
                   select m;                  

    //return the messages
    return messages;
}

这将导致SQL类似于以下内容:(假设您使用LINQ to SQL或LINQ to EF与Microsoft SQL提供程序)

SELECT [t0].[id], ... other columns ...
FROM [Messages] AS [t0]
INNER JOIN [MessageReceivers] AS [t1] ON [t0].[id] = [t1].[message_id]