Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have tables Message and Image that I'm joining. The tables look like this:

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

Not all messages will have an ImageID. Here's my current join:

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

I then bind resultTable to a ListView that needs the Path column from the Image table. My current join only returns messages with images. How would I select all messages, but if the message has an ImageID != null, then assign it a value for Path? I assume I should change this line: on m.ImageID equals i.ImageID at minimum.

like image 222
TestWell Avatar asked May 30 '15 02:05

TestWell


People also ask

Does Linq ever return null?

It will return an empty enumerable. It won't be null.

Can we use joins in Linq?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.

Is null SQL in Linq?

NULL in SQL means, "value absent, will match any comparison", whereas null in . NET means "no object, comparing against null will always yield false". Save this answer.

What is Groupjoin in Linq?

The group join is useful for producing hierarchical data structures. It pairs each element from the first collection with a set of correlated elements from the second collection. For example, a class or a relational database table named Student might contain two fields: Id and Name .


1 Answers

You're currently doing an inner join, but you can use DefaultIfEmpty() to create a left outer join. This will also return the null records.

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 : ""
    };
like image 60
Nic Avatar answered Sep 28 '22 01:09

Nic