从收到的数据存储过程中填充自定义C#对象

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# */ 

使用ADO.NET,在使用参数执行SP的SqlCommand对象上打开SqlDataReader。 使用SqlDataReader.NextResult方法获取第二个结果集。

基本上:

 SqlConnection cn = new SqlConnection(""); cn.Open(); SqlCommand Cmd = new SqlCommand("", 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(); 

您可以使用ADO.net并设计一个数据集,它将为您创建类,以便您的查询将执行并读入存储您获得的数据的类。

http://msdn.microsoft.com/en-us/library/aa581776.aspx

这是一个关于如何创建数据访问层的优秀教程,这听起来像你想要做的。

 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 users = new List; List adresses = new List; 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 } 

Linq to SQL,Entity Framework或NHibernate将是我的建议。

查看企业库,特别是Microsoft软件模式和实践中的数据访问块。 即使你不使用它,你也可以窃取,呃……从中借用代码来做你想做的事。

http://www.codeplex.com/entlib