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

前端 未结 2 1694
你的背包
你的背包 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:39

    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()
    
    0 讨论(0)
  • 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")}
    
    0 讨论(0)
提交回复
热议问题