我有一个名为Products and Categories的表,其中一个Products表的行包含这样的数据:
ProductId,ProductName,CategoryId
并且类别包括
CategoryId,CategoryInfo
所以我使用ado.net(例如
)使用ExecudeReader()
获取行
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())
});
}
}
}
但我想从Categories表中获取CategoryInfo而不使用其他ExecuteReader()
。如果是,我可以为产品和类别创建一个实体类吗?我是如何做到的?还是存在另一种最佳做法?
答案 0 :(得分: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()
要说清楚 - 您必须在CategoryInfo
课程中拥有ProductEntity
属性。