2013-03-13 251 views
0

我有表名为Products和类别,产品表的行包括这样的数据之一:创建关系类对象

ProductId,ProductName,CategoryId 

和类别包括

CategoryId,CategoryInfo 

所以我m到处使用ExecudeReader()行使用ado.net像

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()) 
        }); 
       } 
      } 
     } 

但我想从Cat得到CategoryInfo同样没有使用ExecuteReader()。如果是,我可以为产品和类别创建一个实体类我该怎么做?或者存在另一个最佳实践?

+0

cmdText作为命令文本时有什么值?如果可能的话, – MarcinJuraszek 2013-03-13 07:20:22

+0

使用连接 – TalentTuner 2013-03-13 07:21:48

回答

1

更改您的查询:

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

并获得CategoryInfo由查询返回的第四个元素:

CategoryInfo= reader[3].ToString() 

要清楚 - 你必须有ProductEntity类中CategoryInfo属性。