Search code examples
c#enterprise-library

Enterprise library Rewriting the Code to Save data and return value


Without Enterprise Data library,I am using the below code to insert some thing to DB and reading the return value from that

int result = 0;
using (SqlConnection myConnection = 
    new SqlConnection(AppConfiguration.ConnectionString))
{
     SqlCommand myCommand = new SqlCommand("SaveUser", myConnection);
     myCommand.CommandType = CommandType.StoredProcedure;
     myCommand.Parameters.AddWithValue("@location", objUser.Location);

     DbParameter returnValue;
     returnValue = myCommand.CreateParameter();
     returnValue.Direction = ParameterDirection.ReturnValue;
     myCommand.Parameters.Add(returnValue);

     myConnection.Open();
     myCommand.ExecuteNonQuery();
     result = Convert.ToInt32(returnValue.Value);
     myConnection.Close();
}

How can i do the same in Enterprise Datalibrary ? I want to return value from the stored procedure being called.


Solution

  • You can try to do it in similar way. "YourDb" should be defined in your config file.

    int result = 0;
    
    Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("YourDb");
    DbCommand myCommand = db.GetStoredProcCommand("SaveUser");
    db.AddInParameter(myCommand, "location", DbType.String, objUser.Location);
    db.ExecuteNonQuery(myCommand);
    result = Convert.ToInt32(db.GetParameterValue(myCommand, "returnValue"));