如何将下面的查询结果转换为List<Product>
类型?
只想返回一些结果并将其分配给products变量:
using (SqlConnection sqlConnection = new SqlConnection(LOCAL))
{
sqlConnection.Open();
using (SqlCommand cmd = sqlConnection.CreateCommand())
{
cmd.CommandText = "select Sku from product";
cmd.CommandType = CommandType.Text;
using (SqlDataReader reader = cmd.ExecuteReader()) // ????
{
// ??????????
}
}
}
var products = new List<Product>();
我需要products
变量来包含结果。如何才能做到这一点?
答案 0 :(得分:3)
在调用数据库之前创建列表并创建新的产品对象并映射它。
var products = new List<Product>();
using (SqlConnection sqlConnection = new SqlConnection(LOCAL))
{
sqlConnection.Open();
using (SqlCommand cmd = sqlConnection.CreateCommand())
{
cmd.CommandText = "select Sku from product;
cmd.CommandType = CommandType.Text;
using (SqlDataReader reader = cmd.ExecuteReader()) ????
{
var product = new Product();
//Grab the values using the SqlDataReader and map it to the properties
//...
//Add code e.g. product.Id = reader.GetField<int>("Id");
//...
products.Add(product);
}
}
}
答案 1 :(得分:1)
将每个产品添加到列表中
var products = new List<Product>();
using (SqlDataReader reader = cmd.ExecuteReader()) ????
{
Product p = new Product();
p.Name = reader.Field<string>("Name");
p.Sku = reader.Field<string>("Sku");
// etc.
products.Add(p);
}
答案 2 :(得分:0)
在像这样的情况下,像Dapper这样的简单ORM非常宝贵。
让我们假设你的类Product
是这样的,它反映了db
public class Product
{
public string Name {get;set;}
public string Sku {get; set;}
public decimal Price {get; set;}
... and so on for the other fields ....
}
现在使用Dapper获取List<Product>
,只需编写
public List<Product> SelectAllProducts()
{
using (IDbConnection connection = new SqlConnection(LOCAL))
{
string query = @"SELECT * FROM PRODUCTS ORDER BY Name";
return connection.Query<Product>(query, null).ToList();
}
}