title: Fastest way to retrieve data from database
body: <p>I am working on a ASP.NET project with C# and Sql Server 2008.</p>
  
  <p>I have three tables:</p>
  
  <p><img src="https://i.stack.imgur.com/2bGzV.png" alt="Users"> <img src="https://i.stack.imgur.com/4OXWK.png" alt="DataFields"> 
  <img src="https://i.stack.imgur.com/tH8nI.png" alt="DataField Values"></p>
  
  <p>Each user has a specific value for each data field, and this value is stored in the DataFieldsValues.</p>
  
  <p>Now I want to display a report that looks like this:</p>
  
  <p><img src="https://i.stack.imgur.com/e76bV.png" alt="enter image description here"></p>
  
  <p>I have created the objects <code>User</code>, and <code>DataField</code>. In the DataField object, there is the Method <code>string GetValue(User user)</code>, in which I get the value of a field for a certain user.</p>
  
  <p>Then I have the list of Users <code>List&lt;User&gt; users</code> and the list of DataFields <code>List&lt;DataField&gt; fields</code> and I do the following:</p>
  
  <pre><code>string html = string.Empty;
  html += "&lt;table&gt;";
  html += "&lt;tr&gt;&lt;th&gt;Username&lt;/th&gt;";
  foreach (DataField f in fields)
  {
     html += "&lt;th&gt;" + f.Name + "&lt;/th&gt;";
  }
  html += "&lt;/tr&gt;"
  
  foreach (User u in users)
  {
     html += "&lt;tr&gt;&lt;td&gt;" + u.Username + "&lt;/td&gt;"
     foreach (DataField f in fields)
     {
        html += "&lt;td&gt;" + f.GetValue(u) + "&lt;/td&gt;";
     }
     html += "&lt;/tr&gt;"
  }
  Response.Write(html);
  </code></pre>
  
  <p>This works fine, but it is <strong>extremely</strong> slow, and I am talking about 20 users and 10 data fields. Is there any better way in terms of performance to achieve this? </p>
  
  <p>EDIT: For each parameter inside the classes, I retrieve the value using the following method:</p>
  
  <pre><code>public static string GetDataFromDB(string query)
  {
      string return_value = string.Empty;
      SqlConnection sql_conn;
      sql_conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XXXX"].ToString());
      sql_conn.Open();
      SqlCommand com = new SqlCommand(query, sql_conn);
      //if (com.ExecuteScalar() != null)
      try
      {
          return_value = com.ExecuteScalar().ToString();
      }
      catch (Exception x)
      {
      }
      sql_conn.Close();
      return return_value;
  } 
  </code></pre>
  
  <p>For instance:</p>
  
  <pre><code>public User(int _Id)
  {
  this.Id = _Id
  this.Username = DBAccess.GetDataFromDB("select Username from Users where Id=" + this.Id)
   //...
  }
  </code></pre>