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;
my开发者_C百科Command.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.
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"));
You can shorten it using an overload of ExecuteNonQuery:
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("YourDb");
db.ExecuteNonQuery("SaveUser", objUser.Location);
int result = Convert.ToInt32(db.GetParameterValue(myCommand, "returnValue"));
where SaveUser is the proc name and objUser.Location is the input parameter
You must add return parameter to the command object before executing the query.
db.AddParameter(myCommand, "returnvalue", DbType.String, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);
--Execute the query here using ExecuteNonQuery
result = Convert.ToInt32(db.GetParameterValue(myCommand, "returnValue"));
精彩评论