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
With entities you have a container and assess your tables by their name. This where clause filters results by a fields value and can be concatenated with more values. The parts in {} are for you to change to match your entities. This query is an IEnumerable(Of {your entity})
- great for databinding.
Dim query = model.{table name}.Where(Function(o) o.{column name} = {some value}).ToList()
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")}