title: Dynamically Pivot in LINQ: Pivoted Columns Determined at Runtime
body: <p>Let's say I have three tables. Basically, one table of things, one table describing the possible attributes of the things, and a bridge table providing the values for those attributes for a particular thing. This lets you do dynamic metadata.</p>
  
  <p>Users can add metadata properties at any time, and then they can provide values for those properties for any thing in the "things" table.</p>
  
  <p>So like this:</p>
  
  <pre><code>Table: Persons
  PersonID | FirstName | LastName 
  1        | Bob       | Jones
  2        | Fred      | Smith
  3        | Sally     | Doe
  
  Table: Properties
  PropertyID | Name
  1          | SupervisorName
  2          | Age
  3          | Birthday
  4          | EmployeeNumber
  5          | Hometown
  
  Table: PropertyValues
  PersonID | PropertyID | PropertyValue
  1        | 1          | Frank Grimes
  1        | 2          | 47
  2        | 2          | 35
  2        | 4          | 1983738
  2        | 3          | 5/5/1978
  3        | 3          | 4/4/1937
  3        | 5          | Chicago, IL
  </code></pre>
  
  <p>So, users want to be able to view a report of these properties. Maybe I want to see a table containing the age and birthday of all employees. There would be blanks in the table if those values aren't populated for those users. Then maybe I want to see a report that includes supervisor, age and birthday--I should be able to generate that table on the fly as well.</p>
  
  <p>Now, in order to do this with SQL, I would dynamically construct a query and add a join to that query for each property that I want to pivot up to the top. That's how it works now.</p>
  
  <p>If I wanted to do this in LINQ, and I knew which properties to pivot while writing the code, I could do that too--I'd just use GroupJoin().</p>
  
  <p>What I don't know is how to dynamically construct a LINQ query that would allow me to pivot any number of properties at runtime, without knowing what they are ahead of time.</p>
  
  <p>Any ideas?</p>
  
  <p>(Before you knee-jerk mark this as a duplicate, know that I did a fair amount of StackOverflow research before posting this question, and if this exact question has been asked before, I couldn't find it.)</p>