0

I have table named Products and Categories, one of Products table's row include data like that:

ProductId,ProductName,CategoryId

And Categories include

CategoryId,CategoryInfo

So I m getting rows with using ExecudeReader() using ado.net like

List<ProductEntity> lst = new List<ProductEntity>();
using (SqlConnection connection = new SqlConnection(constr))
        {
            SqlCommand command = connection.CreateCommand();
            command.CommandText = "select ProductId,ProductName,CategoryId from Products";
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    lst.Add(new ProductEntity()
                    {
                        ProductId = int.Parse(reader[0].ToString()),
                        ProductName= reader[1].ToString(),
                        CategoryId=int.Parse(reader[2].ToString())
                    });
                }
            }
        }

But I want to get CategoryInfo from Categories table too without using another ExecuteReader(). Can I create one entity class for both Product and Category if yes How I do that? Or another best practice exist?

2
  • What value cmdText has when used as command text? Commented Mar 13, 2013 at 7:20
  • use joins if it is possible Commented Mar 13, 2013 at 7:21

1 Answer 1

1

Change your query to:

SELECT p.ProductId, p.ProductName, p.CategoryId, c.CategoryInfo
FROM Products p
JOIN Categories c ON c.CategoryId = p.CategoryId

And get CategoryInfo as a fourth element returned by query:

CategoryInfo= reader[3].ToString()

To make it clear - you have to have CategoryInfo property within ProductEntity class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.