Scenario:
Create a DB command to run stored procedures
Solution:
Behavioral Pattern is used to encapsulate a command as an object.
Example: Create a DB command to run stored procedures
- Create a DataCommand which takes name of SP and parameters for it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | class DataCommand
{
//name = SP name
public DataCommand(string name)
{
Name = name;
Parameters = new List<DataCommandParameter>();
}
public class DataCommandParameter
{
public DataCommandParameter(string name, object value)
{
Name = name;
Value = value;
}
}
} |
- Create a DataCommand with SP and params and execute it against the database
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | class Users
{
static async Task Main(string[] args)
{
var param = new[]
{
new DataCommandParameter {Name = "UserName", Value = "Test User"}
};
var command = new DataCommand
{
Name = "GetUsersByName",
Parameters = param.ToList()
};
IEnumerable<ExpandoObject> result;
if (ExecuteQuery(command, out result))
{
...
}
}
} |
No comments:
Post a Comment