title: LINQ to Entities - Initializing complex objects (Dictionary or List<KeyValuePair>)
body: <p>I am required to represent data on a tree, with each node having <code>id</code>, <code>text</code> and several <code>attributes</code>.</p>
  
  <p>I've tried keep my <code>attributes</code> property generic, and initialize it using LINQ to Entities.</p>
  
  <hr />
  
  <p><strong>Attempt 1</strong>:  </p>
  
  <p>With my class as:</p>
  
  <pre><code>public class TreeNode
  {
      public int id { get; set; }
      public string text { get; set; }
      public Dictionary&lt;string, object&gt; attributes { get; set; }
      public int? parent { get; set; }
  }
  </code></pre>
  
  <p>I tried initializing:</p>
  
  <pre><code>List&lt;TreeNode&gt; taskItems = new List&lt;TreeNode&gt;();
  using (var database = new MyDatabase())
  {
      taskItems =
      (
          from t in database.Task
          select new TreeNode()
          {
              id = t.ID,
              text = t.Name,
              attributes = new Dictionary&lt;string, object&gt;()
              {
                  { "Color", t.Color },
                  { "Category", t.Category }
              },
              parent = t.ParentID
          }
      )
      .ToList();
  }
  </code></pre>
  
  <p>The above fails with the error </p>
  
  <blockquote>
    <p><strong>Only list initializer items with a single element are supported in LINQ to Entities.</strong></p>
  </blockquote>
  
  <hr />
  
  <p><strong>Attempt 2</strong>:  </p>
  
  <p>I tried <code>List&lt;KeyValuePair&gt;</code> instead of the <code>Dictionary</code>:</p>
  
  <pre><code>public class TreeNode
  {
      public int id { get; set; }
      public string text { get; set; }
      public List&lt;KeyValuePair&lt;string, object&gt;&gt; attributes { get; set; }
      public int? parent { get; set; }
  }
  </code></pre>
  
  <p>I tried initializing:</p>
  
  <pre><code>List&lt;TreeNode&gt; taskItems = new List&lt;TreeNode&gt;();
  using (var database = new MyDatabase())
  {
      taskItems =
      (
          from t in database.Task
          select new TreeNode()
          {
              id = t.ID,
              text = t.Name,
              attributes = new List&lt;KeyValuePair&lt;string, object&gt;&gt;()
              {
                  new KeyValuePair&lt;string, object&gt;("Color", t.Color),
                  new KeyValuePair&lt;string, object&gt;("Category", t.Category)
              },
              parent = t.ParentID
          }
      )
      .ToList();
  }
  </code></pre>
  
  <p>This time the above fails with the error </p>
  
  <blockquote>
    <p><strong>Only parameterless constructors and initializers are supported in LINQ to Entities.</strong></p>
  </blockquote>
  
  <hr />
  
  <p>How can I achieve the initialization of <code>attributes</code> property?</p>