Design Pattern - Behavioral - Command

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
  1. Create a DataCommand which takes name of SP and parameters for it

  2.  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;
                }
    
            }
        }

  3. Create a DataCommand with SP and params and execute it against the database

  4.  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

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...