从数据接收存储过程填充自定义 C# 对象 [英] Filling custom C# objects from data received stored procedure

查看:28
本文介绍了从数据接收存储过程填充自定义 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,在 SqlCommand 对象上打开一个 SqlDataReader,使用参数执行 SP.使用 SqlDataReader.NextResult 方法获取第二个结果集.

Use ADO.NET, open a SqlDataReader on a SqlCommand object executing the SP with the parameters. Use the SqlDataReader.NextResult method to get the second result set.

基本上:

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();

这篇关于从数据接收存储过程填充自定义 C# 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆