Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are reusing the same object over and over, you need to re-create that object. I like <strong>seperating that code in another function</strong>. Here is how I would do it:</p> <p>First you should getproducts like so:</p> <pre><code>public IList&lt;Product&gt; GetProducts(string sortexpression) { StringBuilder sql = new StringBuilder(); sql.Append(" SELECT ProductName, ProductID"); sql.Append(" FROM Products "); if (!string.IsNullOrEmpty(sortExpression)) sql.Append(" ORDER BY " + sortExpression); DataTable dt = Db.GetDataTable(sql.ToString()); return MakeProducts(dt); } </code></pre> <p>So you may ask how does Db.GetDataTable look, well like this:</p> <pre><code> public static DataTable GetDataTable(string sql) { using (DbConnection connection = factory.CreateConnection()) { connection.ConnectionString = connectionString; using (DbCommand command = factory.CreateCommand()) { command.Connection = connection; command.CommandType = CommandType.Text; command.CommandText = sql; using (DbDataAdapter adapter = factory.CreateDataAdapter()) { adapter.SelectCommand = command; DataTable dt = new DataTable(); adapter.Fill(dt); return dt; } } } </code></pre> <p>For simplicity, I am not using sprocs, but you should...anyhow you may ask what does MakeProducts(dt) look like, and that is simply a function to loop and add to a list:</p> <pre><code> private IList&lt;Product&gt; MakeProducts(DataTable dt) { IList&lt;Product&gt; list = new List&lt;Product&gt;(); foreach (DataRow row in dt.Rows) list.Add(MakeProduct(row)); return list; } </code></pre> <p>So here you simply loop each row and make a product object which looks like this:</p> <pre><code> private Product MakeProduct(DataRow row) { int productId = int.Parse(row["ProductId"].ToString()); string name = row["ProductName"].ToString(); return new Product(productId, name); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload