Joining two tables with LINQ, and also returning null records from the second table

I have tables Messageand Imagewith which I connect. The tables look like this:

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

Not all messages will have ImageID. Here is my current connection:

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
    };

Then I bind resultTableto ListViewwhich requires a column Pathfrom the table Image. My current connection returns image messages. How to select all messages, but if the message has ImageID != null, then assign it a value for Path? I guess I should change this line: on m.ImageID equals i.ImageIDat least.

+4
source share
1 answer

, 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 : ""
    };
+4

All Articles