Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Left outer join - Object reference not set to an instance of an object

I have two queries which look like this:

var ret = (from x in _context.CustomUsers
            where x.Name != currentUser
            join c in _context.Claims on x.Name equals c.UserID into m
            from c in m.DefaultIfEmpty()
            select new UsersClients
            {
                UserName = x.Name,
                DefaultClient = "N/A",
                Role = null
            }).ToList();

This returns a list like so:

User1   N/A   null
User2   N/A   null
User3   N/A   null

For this:

var q = (from x in _context.Claims
            where x.Default == true
            select new
            {
                x.UserID,
                x.ClientName
            }).ToList();

This returns a list like so:

User1   Client1
User2   Client3

The first query returns users which do not exist in the second query. I would then like to do a left outer join on both results so I can pull the client from the second query and if it's empty. Replace it with a string.

My third query looks like this:

var p = (from x in ret
            join o in q on x.UserName equals o.UserID into l
            from s in l.DefaultIfEmpty()
            select new UsersClients
            {
                UserName = x.UserName,
                DefaultClient = (s.ClientName == null ? "God dammit work" : s.ClientName),
                Role = null
            }).ToList();

I know why it fails, I just don't know how to fix it. Can anyone help me so the final result looks like this:

    User1   Client2   null
    User2   Client1  null
    User3   Work dammit   null
like image 989
Andrew Kilburn Avatar asked Oct 29 '25 05:10

Andrew Kilburn


1 Answers

It seems s is already null if l is empty. So you need to check s for null too:

DefaultClient = (s == null || s.ClientName == null ? "God dammit work": s.ClientName),

or in C# 6 and with null coalescing operator:

DefaultClient = s?.ClientName ?? "God dammit work",
like image 195
René Vogt Avatar answered Oct 30 '25 19:10

René Vogt