加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 19:33:45 所属栏目:百科 来源:网络整理
导读: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
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("<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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读