Linq-to-Entities: LEFT OUTER JOIN with WHERE clause, calculation and projection

前端 未结 2 1695
你的背包
你的背包 2021-01-25 00:07

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

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-25 00:57

    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")}
    

提交回复
热议问题