我知道人们会大声疾呼这个话题遍及整个互联网。我知道,我已经读过它们。而且我还是不明白。我只想从存储过程的结果中填充对象。现在,此存储过程至少需要两个参数-一个 action 和要查找的。
InternalError
@Action
@customername
只需确定存储过程需要做什么并返回结果。因此,例如,如果我想更新客户,则可以通过对象调用sp:
@Action
这很好。因此,当我只想用sp的结果填充对象时,就会出现问题。在这种情况下,我会将“ Retrieve”作为public class Customer()
{
//properties
public int UpdateCustomer()
{
using (SQLConnection connection = new SqlConnection(Helper.CnnVal("DataConnection")))
{
SQLCommand = new SqlCommand(Helper.Procedure("Customer"), connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameterCollection parameterCollection = command.Parameters;
parameterCollection.Add("@Action", SqlDbType.NVarChar, -1).Value = "Update"
//complete the rest of it....
}
}
}
参数,并将@Action
作为this.customer_name
参数传递给sp。
但是如何将存储过程的结果放入对象中?
我有这个...
@customername
但是我认为它没有用。
很久以前,当我需要填充一个对象时,我曾经为PHP运行“获取”操作。我应该回到这个吗?
答案 0 :(得分:2)
您需要在命令上执行SqlReader,如下所示:
using (var connection = new SqlConnection("Connection"))
using (var command = new SqlCommand("Retrieve", connection))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("@Action", "Retrieve");
command.Parameters.AddWithValue("@name", this.customer_Name);
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var item = new YourClass();
// You can use GetX() methods to get the value of the fields
item.Name = reader.GetString("name");
// You can also access the fields by using bracket notation
item.Age = (int)reader["age"];
// Be careful of nullable fields though!
}
}
}
答案 1 :(得分:0)
使用@ Encrypt0r建议和指导,它可以正常工作:
public void GetCustomer() {
using (SqlConnection connection = new SqlConnection(Helper.CnnVal("DataConnection"))) {
SqlCommand command = new SqlCommand(Helper.Procedure("Customer"), connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@Action", "Retrieve");
command.Parameters.AddWithValue("@name", this.customer_name);
connection.Open();
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
this.tbl_id = (int)reader["tbl_id"];
this.customer_name = (string)reader["customer_name"];
this.customer_id = reader.GetInt32(customer_id);
this.customer_address = (string)reader["customer_address"];
this.customer_city = (string)reader["customer_city"];
this.customer_state = (string)reader["customer_state"];
this.customer_zip = reader.GetInt32(customer_zip);
}
}