我有一个调用存储过程并返回对象列表的方法。我不知道如何将存储过程的结果添加到对象列表中。我试着用模特。添加,但无论如何我正在使用它我收到错误。我在代码中找到了我需要帮助的地方。
这是我的代码:
public List<Models.Type> get_Type(string Type_Group)
{
string connectionName = getConnectionStr();
List<Models.Type> model = null;
string myConnection = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName].ToString();
SqlDatabase db = new SqlDatabase(myConnection);
using (DbCommand command = db.GetStoredProcCommand("LA_Get_Type"))
{
db.AddInParameter(command, "Type_Group", DbType.String, Type_Group);
var result = db.ExecuteReader(command);
try
{
if (result.FieldCount == 0)
model = null;
else
{
while (result.Read())
{
model = new List<Models.Type>()
{
//This is the place I don't know I tried model.Add but not sure what
to have after.
This code is when I have returning just 1 object but I want to
return list of objects
typeID = Convert.ToInt32(result["typeID"].ToString()),
type_group = result["type_group"].ToString(),
type_value = result["type_value"].ToString(),
type_desc = result["type_desc"].ToString(),
type_sort = Convert.ToInt32(result["type_sort"].ToString())
};
}
}
}
catch (Exception ex)
{
}
result.Close();
return model;
}
}
这是我的目标:
public class Type
{
public int typeID { get; set; }
public string type_group { get; set; }
public string type_value { get; set; }
public string type_desc { get; set; }
public int type_sort { get; set; }
}
答案 0 :(得分:1)
更改
while (result.Read())
{
model = new List<Models.Type>()
{
//This is the place I don't know I tried model.Add but not sure what
to have after.
This code is when I have returning just 1 object but I want to
return list of objects
typeID = Convert.ToInt32(result["typeID"].ToString()),
type_group = result["type_group"].ToString(),
type_value = result["type_value"].ToString(),
type_desc = result["type_desc"].ToString(),
type_sort = Convert.ToInt32(result["type_sort"].ToString())
};
}
这样的事情:
model = new List<Models.Type>();
while (result.Read())
{
Models.Type aModel = new Model(){
typeID = Convert.ToInt32(result["typeID"].ToString()),
type_group = result["type_group"].ToString(),
type_value = result["type_value"].ToString(),
type_desc = result["type_desc"].ToString(),
type_sort = Convert.ToInt32(result["type_sort"].ToString())
};
model.Add(aModel);
}
请注意,我为每个结果创建一个新对象,然后将它们逐个添加到列表中。