How to get output parameter value from ExecuteNonQuery in enterprise library (c#)?

Ali Ahmadi picture Ali Ahmadi · Feb 6, 2013 · Viewed 16.6k times · Source

my stored procedure is :

create Procedure spSetUser
(
    @Name NVarchar(50),
    @OrganicTitle NVarchar(30),
    @UserName NVarchar(20),
    @Password NVarchar(16),
    @Result Int Output
)
As
Begin
    Set @Result = -1    
    If Not Exists(Select UserId From dbo.Users Where UserName=@UserName)
    Begin
        Insert Into dbo.Users (Name,OrganicTitle,UserName,[Password]) 
        Values(@Name,@OrganicTitle,@UserName,@Password) 
        Set @Result = SCOPE_IDENTITY()
    End
    Return
End
Go

and my class is (in microsft enterprise library):

[DataObjectMethod(DataObjectMethodType.Insert)]
public Int32 SetUser(UserFieldSet Data)
{
    Int32 Result = 0;
    object[] values = new object[] { Data.Name, Data.OrganicTitle, Data.UserName, Data.Password, Data.UserId };
    Result = Db.ExecuteNonQuery("spSetUser", values);
    return Result;
}

Result is roweffected of execute stored procedure, but I want get value of @Result (output parameter of procedure), How can I get it ?

UserFieldClass is :

public class UserFieldSet
{
    public Int32 UserId;
    public String Name;
    public String OrganicTitle;
    public String UserName;
    public String Password;
}

Tip : I know must use this code for get @Result:

public Int32 SetUser(UserFieldSet Data)
{          
    Int32 Result = 0;
    DbCommand DbCmd = Db.GetStoredProcCommand("spSetUser");
    Db.AddInParameter(DbCmd, "@Name", DbType.String, Data.Name);
    Db.AddInParameter(DbCmd, "@OrganicTitle", DbType.String, Data.OrganicTitle);
    Db.AddInParameter(DbCmd, "@UserName", DbType.String, Data.UserName);
    Db.AddInParameter(DbCmd, "@Password", DbType.String, Data.Password);
    Db.AddOutParameter(DbCmd, "@Result", DbType.Int32, Int32.MaxValue);
    Db.ExecuteNonQuery(DbCmd);
    Result = (Int32)Db.GetParameterValue(DbCmd, "@Result");
    return Result;
}

But I can get it with this methd :

Result = Db.ExecuteNonQuery("spSetUser", values);

Answer

bean picture bean · Feb 6, 2013

Have you tried using ExecuteScalar instead?