C# 使用SqlCommand返回值

C# 使用SqlCommand返回值,c#,.net,sql-server-2008,csla,C#,.net,Sql Server 2008,Csla,我正在尝试获取SQL 2008 server上存储过程的结果集和返回值。当我在sql management studio中运行该过程时,我会得到结果集和返回值 但是,当我尝试在C#4.0中获取该值时,该参数的值为null。这是我的C#代码: 使用(ConnectionManager cn=ConnectionManager.GetManager(CultureInfo.CurrentCulture.Name)) { 使用(SqlCommand cm=cn.Connection.CreateCom

我正在尝试获取SQL 2008 server上存储过程的结果集和返回值。当我在sql management studio中运行该过程时,我会得到结果集和返回值

但是,当我尝试在C#4.0中获取该值时,该参数的值为null。这是我的C#代码:

使用(ConnectionManager cn=ConnectionManager.GetManager(CultureInfo.CurrentCulture.Name))
{
使用(SqlCommand cm=cn.Connection.CreateCommand())
{
cm.CommandText=“此处的进程名称”;
cm.CommandType=CommandType.StoredProcess;
cm.Parameters.AddWithValue(“@ApplicationId”,ApplicationId);
cm.Parameters.AddWithValue(“@Index”,Index);
如果(页面大小>0)
cm.Parameters.AddWithValue(“@PageSize”,PageSize);
添加(“@ReturnValue”,SqlDbType.Int);
cm.Parameters[“@ReturnValue”].Direction=ParameterDirection.ReturnValue;
使用(IDataReader dr=cm.ExecuteReader())
{
SafeDataReader sdr=新的SafeDataReader(dr);
while(sdr.Read())
{
UserApplicationEntity uae=新的UserApplicationEntity();
uae.UserId=sdr.GetGuid(“UserId”);
uae.ExternalId=sdr.GetString(“ExternalId”);
结果.价值.收集.添加(阿联酋);
}
Result.Value.TotalResults=(int)cm.参数[“@ReturnValue”].Value;
}
}
}

我调用Result.Value.TotalResults=(int)cm.Parameters[“@ReturnValue”].Value的最后一行;值为null的位置。在我找到的每一篇教程或帖子中,我似乎都做得很正确。在这一点上,我想我只是错过了一些小东西,需要另一双眼睛。我也尝试过在所有其他参数之前设置return参数,因为我在MS site上找到的一篇帖子说我需要设置,但不管它在哪里,它都返回null。

返回值在数据库响应的最后发送,所以在访问返回值之前,您必须完全读取结果集

SafeDataReader
类做什么?它是否可能阻止读取整个结果集


尝试使用数据读取器的块将读取返回值的代码移到
之外。这可能有助于将响应推进到结果集之外,以便返回值可用。

必须将其移出using块,以使其关闭读卡器。从未想过会是这样。谢谢
using (ConnectionManager<SqlConnection> cn = ConnectionManager<SqlConnection>.GetManager(CultureInfo.CurrentCulture.Name))
{
    using (SqlCommand cm = cn.Connection.CreateCommand())
    {
        cm.CommandText = "Name of proc here";
        cm.CommandType = CommandType.StoredProcedure;

        cm.Parameters.AddWithValue("@ApplicationId", ApplicationId);                                        
        cm.Parameters.AddWithValue("@Index", Index);

        if (PageSize > 0)
            cm.Parameters.AddWithValue("@PageSize", PageSize);

        cm.Parameters.Add("@ReturnValue", SqlDbType.Int);
        cm.Parameters["@ReturnValue"].Direction = ParameterDirection.ReturnValue;

        using (IDataReader dr = cm.ExecuteReader())
        {
            SafeDataReader sdr = new SafeDataReader(dr);
            while (sdr.Read())
            {
                UserApplicationEntity uae = new UserApplicationEntity();
                uae.UserId = sdr.GetGuid("UserId");
                uae.ExternalId = sdr.GetString("ExternalId");
                Result.Value.Collection.Add(uae);
            }

            Result.Value.TotalResults = (int)cm.Parameters["@ReturnValue"].Value;
        }
    }
}