I currently have 2 tables:
Table1, with the following columns:
- Id, TypeId, VersionId, AnotherColumn1, AnotherColumn2, AnotherColumn3
Table2, with the following columns:
- Id, TypeId, VersionId, DifferentColumn1, DifferentColumn2
The only thing these 2 tables have in common are TypeId and VersionId.
I am trying to get only the TypeId and VersionId from Table1 AS LONG as that specific **Type Id + VersionId combination **is not in Table 2.
I have tried the following:
var result1 = this.Table2
.Select(k => new { TypeId = k.TypeId, VersionId = k.VersionId })
.ToArray() // Trying to first select all possible TypeId + VersionId combinations from Table2
var finalResult = this.Table1
. // This is where I am lost, should I use a `.Except`?, some kind of `.Where`?
2
Answers
This should be possible with grouping a left outer join using
DefaultIfEmpty
:This may look a bit complicated but we essentially do an outer join between the tables on the TypeId and VersionId. When fetching the grouped result of that join we have to tell EF to exclude any cases where Table2 would be #null, otherwise we would get a collection with 1 #null element. (There may be a more optimal way to get this to work, but the above does work) This is grouped by the combination of values requested (TypeId and VersionId from Table 1). From there it is just filtering out the results where there are no Table2 records, and selecting the "Key" from the grouping, which is our desired values.