使用LINQ连接两个表,同时还从第二个表

时间:2015-05-30 02:21:08

标签: c# .net entity-framework linq linq-to-entities

我有加入的MessageImage表格。表格如下所示:

Message(MessageID, TimeStamp, Text, RoomID, ImageID, UserID)
Image(ImageID, Path, Type, UserID)

并非所有邮件都会有ImageID。这是我目前的加入:

List<Message> messages = Message.GetAll();
List<Image> images = Image.GetAll();

var resultTable = from m in messages 
    join i in images 
    on m.ImageID equals i.ImageID
    select new
    {
        MessageID = m.MessageID,
        TimeStamp = m.TimeStamp,
        Text = m.Text,
        RoomID = m.RoomID,
        ImageID = m.ImageID,
        UserID = m.UserID,
        Path = i.Path // Nullable
    };

然后我将resultTable绑定到需要ListView表中的Path列的Image。我当前的连接仅返回带有图像的消息。如何选择所有邮件,但如果邮件包含ImageID != null,则为其分配Path的值?我想我应该改变这一行:on m.ImageID equals i.ImageID至少。

1 个答案:

答案 0 :(得分:4)

您目前正在进行内部联接,但您可以使用DefaultIfEmpty() to create a left outer join。这也将返回空记录。

var resultTable = from m in messages 
    join i in images on m.ImageID equals i.ImageID into imgJoin
    from img in imgJoin.DefaultIfEmpty()
    select new
    {
        MessageID = m.MessageID,
        TimeStamp = m.TimeStamp,
        Text = m.Text,
        RoomID = m.RoomID,
        ImageID = m.ImageID,
        UserID = m.UserID,
        Path = img != null ? img.Path : ""
    };