Notes on the code blocks seen below
- Both code blocks do the same thing. They have the same interface and they return the same data.
- Code block #2 is considerably less code and easier to read.
- Other than the obvious differences, the only notable difference is the "Serializable" attribute.
Why would there be so much effort to use a command object? Is it just so that the code will run on the app server rather than the client?
Code block #1
public static string GetDataOnSomething(int id)
{
GetDataOnSomethingCommand result;
result = DataPortal.Execute<GetDataOnSomethingCommand>
(new GetDataOnSomethingCommand(id));
return result.ReturnedData;
}
[Serializable()]
private class GetDataOnSomethingCommand : CommandBase
{
private int _id;
private string _returnedData = string.Empty;
public string ReturnedData
{
get { return _returnedData; }
}
public GetDataOnSomethingCommand(int id)
{
_id = id;
}
protected override void DataPortal_Execute()
{
using (SqlConnection cn = new SqlConnection(Database.YourConnection))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "storedProc";
cm.Parameters.AddWithValue("@Id", _id);
string returnedData = cm.ExecuteScalar().ToString();
_returnedData = returnedData;
}
}
}
}
Code block #2
public static string GetDataOnSomething(int id)
{
using (SqlConnection cn = new SqlConnection(Database.YourConnection))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "storedProc";
cm.Parameters.AddWithValue("@Id", id);
string returnedData = cm.ExecuteScalar().ToString();
}
}
return returnedData;
}
thanks, Ryan
Thanks for the replies.
I think typically you'd also expose the command object itself to the UI.
This statement confused me a bit. Can you explain?
thanks, Ryan
Copyright (c) Marimer LLC