public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Address
{
public string City { get; set; }
public string Country { get; set; }
}
/*
* There are 2 c# objects i have shown
* There is a stored procedure in my application which
* returns data for both objects simultaneously
* eg
* select FirstName, LasteName from Users where something="xyz"
* select City,Country from Locations where something="xyz"
*
* both queries are run by single procedure
* Now how can i fill both objects with from that stored procedure in asp.net using c#
*/
答案 0 :(得分:7)
使用ADO.NET,在使用参数执行SP的SqlCommand对象上打开SqlDataReader。使用SqlDataReader.NextResult方法获取第二个结果集。
基本上:
SqlConnection cn = new SqlConnection("<ConnectionString>");
cn.Open();
SqlCommand Cmd = new SqlCommand("<StoredProcedureName>", cn);
Cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
while ( dr.Read() ) {
// populate your first object
}
dr.NextResult();
while ( dr.Read() ) {
// populate your second object
}
dr.Close();
答案 1 :(得分:3)
您可以使用ADO.net并设计一个数据集,它将为您创建类,以便您的查询将执行并读入存储您获得的数据的类。
http://msdn.microsoft.com/en-us/library/aa581776.aspx
这是一个关于如何创建数据访问层的优秀教程,这听起来像你想要做的。
答案 2 :(得分:3)
using(SqlConnection connexion = new Sqlconnection(youconenctionstring))
using(SqlCommand command = conenxion.Createcommand())
{
command.Commandtext = "yourProcName";
command.CommandType = CommandType.StoredProcedure;
command.Paramters.Add("@yourparam",yourparamvalue);
connexion.Open();
SqlDataReader reader = command.ExecuteReader();
List<User> users = new List<User>;
List<Adress> adresses = new List<User>;
while(read.Read())
{
User user = new User();
user.firstName = (string) read["FirstName"];
users.Add(user);
}
read.NextResult();
while(read.Read)
{
Address address = new Address();
address.City = (string) read["Name"];
adresses.Add(address);
}
//make what you want with your both list
}
答案 3 :(得分:1)
Linq to SQL,Entity Framework或NHibernate将是我的建议。
答案 4 :(得分:0)
查看企业库,特别是Microsoft软件模式和实践中的数据访问块。即使你不使用它,你也可以窃取,呃......借用代码来做你想做的事。