我有表Message
和Image
,我要加入。表看起来像这样:
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
绑定到需要Image
表中的Path
列的ListView
。我当前的连接只返回带有图像的消息。我如何选择所有消息,但如果消息有ImageID != null
,然后为Path
分配一个值?我想我应该至少改变这一行:on m.ImageID equals i.ImageID
您目前正在进行内部连接,但是您可以使用DefaultIfEmpty()来创建左外部连接。这也将返回空记录。
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 : ""
};