I have a database with a "dictionary" like this:
Id (INT) | Key (VARCHAR) | Value (VALUE) | ForeignKey (INT?)
------------------------------------------------------------
1 | foo | bar | 23
2 | bar | foo | NULL
3 | foobar | value | NULL
4 | foobar | othervalue | 47
Now I want to get all keys and values for a specific foreign key, but also all foreign keys that are NULL, so that the result looks like this:
ForeignKey = 23: ForeignKey = 47:
foo | bar bar | foo
bar | foo foobar | othervalue
foobar | value
Originally I tried this approach:
dbContext.Table
.Where(t => t.ForeignKey == 47 || t.ForeignKey == null)
but that gives me foobar
twice.
I then though about multiple requests and unionizing the results:
var t1 = _dbContext.Table
.Where(t => t.ForeignKey == 47);
var t2 = _dbContext.Table
.Where(t => t.ForeignKey == null && !t1.Any(tt => tt.Key == t.Key));
var final = t1.Union(t2);
This seemingly works, but it creates this SQL (roughly) which seems excessive with three SELECT, three WHERE and a UNION
SELECT [t1].[Id], [t1].[Key], [t1].[Value], [t1].ForeignKey
FROM [Table] AS [t1]
WHERE [t1].[ForeignKey] = 47
UNION
SELECT [t2].[Id], [t2].[Key], [t2].[Value], [t2].ForeignKey
FROM [Table] AS [t2]
WHERE [t2].[ForeignKey] IS NULL AND NOT (EXISTS (
SELECT 1
FROM [Table] AS [t3]
WHERE ([t3].[ForeignKey] = 47) AND ([t3].[Key] = [t2].[Key])))
I just have a gut feeling that "there's got to be a better way"... so, is there? How can I get keys and values for a specific foreign key, but also keys not already fetched that are NULL?