I\'m having a very difficult time figuring out how to translate a simple SQL LEFT OUTER JOIN on multiple columns and a where clause into a working Linq-to-Entities query. There
First, if you group on multiple fields, you are comparing anonymous types, so the part
On
New (t2.Field(Of String)("tableid1"), t2.Field(Of String)("tableid2"))
Equals
(t1.Field(Of String)("tableid1"), t1.Field(Of String)("tableid2"))
should be changed into the syntax for creating anonymous types (same as you use later in the query):
On
New With {.id1 = t2.Field(Of String)("tableid1"),
.id2 = t2.Field(Of String)("tableid2")}
Equals
New With {.id1 = t1.Field(Of String)("tableid1"),
.id2 = t1.Field(Of String)("tableid2")}
but
In C# this would be enough, because with anonymous types, the C# compiler uses equality based on values. For some reason however, with VB this is different, it uses reference equality. So the Equals
is always false
, because the first object is not the same object as the second.
Fortunately, VB has the Key
keyword that lets you indicate properties to be used when comparing anonymous objects. So the final syntax is:
On
New With {Key .id1 = t2.Field(Of String)("tableid1"),
Key. id2 = t2.Field(Of String)("tableid2")}
Equals
New With {Key .id1 = t1.Field(Of String)("tableid1"),
Key .id2 = t1.Field(Of String)("tableid2")}